"""fp="python3/math/math.1y.txt"

f=open(fp,"r+")
line=f.readline(10000)
print("read:",line)


f=open(fp,"w+")
s=input("输入:")
f.writelines(s)
f.close()

f=open(fp,"w+")
s=str(c_x)
s2=str(c_y)
f.writelines([s+"\n",s2+"\n"])
f.close()
"""
#!/usr/bin/env pyahont3

"""
练习作业：01
1. 打印 Hello Worwd
"""
print("Hello Worwd")
my_name=input("what is your name?")
print(f"你好,{my_name}")
#!/usr/bin/env pyahont3

"""
练习作业：02
2. 计算 1+2+3...+100，打印出最终结果 [使用变量、循环]
"""

N=1000
a=1
b=0
while a<=N:
    b=b+a
    a=a+1
print(b)
#!/usr/bin/env pyahont3

import os
"""
练习作业：05
1. 读写文件 



fp="./temp/temp.txt"

if not os.path.exists("./temp"):
    os.makedirs("./temp")

f=open(fp,"r+")
line=f.readline(4)
print("read:",line)


f=open(fp,"w+")
s=input("输入:")
f.writelines(s)
f.close()



print("Hello Worwd")
my_name=input("what is your name?")
print(f"你好,{my_name}")

fp="./temp/temp.txt"


f=open(fp,"r+")
line=f.readline(100)
print("你好:",line)

f=open(fp,"w+")
s=my_name
f.writelines(s)
f.close()
"""


fp="python3/study/base.txt"

f=open(fp,"r+")
line=f.readline(10000)
print("read:",line)


f=open(fp,"w+")
s=input("输入:")
f.writelines(s)
f.close()
#!/usr/bin/env pyahont3

"""
练习作业：04
4. 计算打印 杨辉三角 传入参数 L 为打印的层数； [使用函数递归调用]
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
"""
def z(x,y):
    if y==0 or x==y:
        return 1
    return z(x-1,y-1)+z(x-1,y)
L=int(input("层数"))
for x in range(0,L):
    for y in range(0,x):
        print(z(x,y),end="  ")
    print("1")






#L=10

#L=10
#n=1  #行数
#while n<=L:
#    pass

#a:行数
#b:列数
#返回对应行列值

"""def yang(a,b):
    a=int(input("行数"))
    b=0
    c=a+b
    print(a,c,a)

yang()"""
#input:x,y
#return:杨辉三角在第x行、第y列的值 x,y基于1
# 1
# 1,1
# 1,2,1
# 1,3,3,1
# 1,4,6,4,1
# 1,5,10,10,5,1
# 1,6,15,20,15,6,1
# 1,7,21,35,35,21,7,1
# 1,8,28,56,70,56,28,8,1
# 1,9,36,84,126,126,84,36,9,1
"""
def san(a):
    a=int(input("?"))
    a=a+1
    b="*"
    for i in range(2,a,1):
        print((b*i).center(i))
print("a",end="")
print("b",end="")
print()
def z(x,y):
    if x==1:
        return 1
    if y==x:
        return 1
    return z(x-1,y-1)+z(x-1,y)
    print(z)
for x in range(1,10):
    for y in range(1,x):
        def z(x,y):
            if x==1:
                return 1
            if y==x:
                return 1
            return z(x-1,y-1)+z(x-1,y)
        if y<x:
            print(z(x,y),end="")
        if y==x:
            print("")
def z(x,y):
    if y==1:
        return 1
    if y>=x:
        return 0
    return z(x-1,y-1)+z(x-1,y)
for x in range(1,5):
    for y in range(1,5):
        print(z(x,y))
        def main():
if __name__ ==  "__main__":
    a=int(input("?"))
    main()
    san(10)
def z(x,y):
    if x==1 and y==1:
        s=1
    if x!=1 and y!=1:
for x in range(1,10):
    for y in range(1,10):
        def z(x,y):
            if y==1:
                return 1
            if y>=x:
                return 0
            return z(x-1,y-1)+z(x-1,y)
            print(z(x,y))
        z(x,y)
def z(n):
    a=[1]
    if n==0:
        return a
    return [x+y for x, y in zip([0]+z(n-1),z(n-1)+[0])]
for i in range(9):
    print(z(i))
def z(x,y):
    a=[1]
    if x==0:
        return a
    return [z(x-1,y-1)+z(x-1,y)]
for x in range(1,5):
    for y in range(1,x):
        print(z(x,y))
def z(x,y):
    if y==1:
        return 1
    if y>x:
        return 1
    return (z(x-1,y-1)+z(x-1,y))
    print(z(x,y))
for x in range(1,10):
    for y in range(1,10):
        z(x,y)
def z(x,y):
    a=[1]
    if x==1:
        return a
    return (x+y for x,y in zip(z(x-1,y-1)+z(x-1,y)))
for x in range(0,5):
    for y in range(0,x):
        print(z(x,y))


L=int(input("?"))
for x in range(0,L):
    for y in range(0,x):
        def z(x,y):
            if y==0 or x==y:
                return 1
            return z(x-1,y-1)+z(x-1,y)
        print(z(x,y),end=" ")
    print("1")"""
#!/usr/bin/env pyahont3

"""
练习作业：03
3. 计算 1+2+3...+100；并打印每一步的结果，例如：1+2=3；1+2+3=6；...; [使用函数]


N=100
a=1
b=0

while a<=N:
    b=b+a
    a=a+1
    c=a=+b
    if a<=N:
        print(f"{b}+{a}={b+a}")
print(b)
    if y==0 or x==y:
        return 1
    return z(x-1,y-1)+z(x-1,y)


def z(b,c):
    d=[]
    e=b
    f=1
    while e>1:
        d.append(f)
        e-=f
        f+=1
    for i in range(1,c+1)
    print


n=101
a=1
b=0
for c in range(a,n):
    b+=c
    print(f"{b}+{c}={b+c}")
"""

# 功能和p一样，更简洁
def p2(e):
    cs=[i+1 for i in range(e)]
    total=sum(cs)
    print("+".join([f"{i}" for i in cs])+f"={total}")

# 打印s+...+e=x的每个元素
def p(s,e):
    c=s
    total=0
    while c<=e:
        total+=c
        if c>1:
            print("+",end="") #打印+，其中第一个数字不打印，end="" 可以让pring不换行
        print(c,end="") #打印每个数字
        c+=1
    print("=",end="")
    print(total) #这里没有end="",这里的print会换行

last=2
max=10
while last<=max:
    p(1,last)
    # p2(last)
    last+=1

exit(0)


n=8
a=1
b=0
c=-1
d=1
def z(a,b,c,d):
    while True:
        e=c+d
        b-=e
        c-=1
        print(f"{e}+",end="")
        if b>=1:
            return z(a,b,c,d)
        else:
            break
while True:
    b+=a
    a+=1
    c+=1
    print(z(a,b,c,d),end=" ")
    print(f"={b}")
    if c>n:
        break
#!/usr/bin/env pyahont3

"""
练习作业：04 
1. 使用pygame 显示窗口 绘制10*10方格，每个方格 50 像素宽
2. 绘制一个圆；可以用方向键控制这个圆在方格内移动
3. 存储圆的位置，在每次重新打开程序时，圆在上次关闭前的方格内
"""
import pygame
import time
import random
fp="python3/study/base.txt"
f=open(fp,"r+")
block_w=60
c_x=int(f.readline(100))
c_y=int(f.readline(100))
N=15
while c_x<=0:
    c_x+=30
while c_y<=0:
    c_y+=30

while c_x>=600:
    c_x-=120
while c_y>=600:
    c_y-=120

while (c_x-30)%60!=0:
    c_x+=1
while (c_y-30)%60!=0:
    c_y+=1
if c_x>600:
    c_x=570
if c_x>600:
    c_x=570
# c_y=block_w//2
c_r=(block_w-6)//2


pygame.init()
screen=pygame.display.set_mode([block_w*N,block_w*N])
screen.fill([255,255,255])



def boo(xx,yy):
    f=block_w/2
    pygame.draw.rect(screen,[0,0,0],[xx,yy,f,f],0)
    pygame.draw.rect(screen,[255,0,0],[xx+f,yy,f,f],0)
    pygame.draw.rect(screen,[0,255,0],[xx,yy+f,f,f],0)
    pygame.draw.rect(screen,[0,0,255],[xx+f,yy+f,f,f],0)

i=0
while i<N:
    j=0
    while j<N:
        pygame.draw.rect(screen,[0,255,0],[i*block_w,j*block_w,block_w,block_w],2)
        #boo(i*block_w,j*block_w)
        j+=1
    i+=1

pygame.draw.circle(screen, [255,0,0], [c_x,c_y], c_r)
pygame.display.flip()
def is_out_range(c_x,c_y):
    if c_x<=0 or c_x>=block_w*N:
        return True
    if c_y<=0 or c_y>=block_w*N:
        return True
    return False

running=True
while running:
    for event in pygame.event.get():
        # print(event)
        if event.type == pygame.QUIT:
            running=False
        elif event.type == pygame.KEYDOWN:
            c_x_old=c_x
            c_y_old=c_y
            # print(event.key)
            if event.key == pygame.K_UP:
                print("向上")
                if not is_out_range(c_x,c_y-1*block_w):                            
                    c_y-=block_w*3
            elif event.key == pygame.K_DOWN:
                print("向下")
                if not is_out_range(c_x,c_y+1*block_w):                            
                    c_y+=1*block_w*2
            elif event.key == pygame.K_LEFT:
                print("向左")
                if not is_out_range(c_x-1*block_w,c_y):                            
                    c_x-=1*block_w*2
            elif event.key == pygame.K_RIGHT:
                print("向右")
                if not is_out_range(c_x+1*block_w,c_y):                            
                    c_x+=1*block_w*3
            pygame.draw.circle(screen, [255,255,255], [c_x_old,c_y_old], c_r)
            boo(c_x_old-(block_w/2),c_y_old-(block_w/2))
            pygame.draw.circle(screen, [255,0,0], [c_x,c_y], c_r)
            pygame.display.flip()



f=open(fp,"w+")
s=str(c_x)
s2=str(c_y)
f.writelines([s+"\n",s2+"\n"])
f.close()

pygame.quit()
import pygame
import time
import random

pygame.init()
pygame.display.set_caption("贪吃蛇 good luck")
screen=pygame.display.set_mode([640,550])
screen.fill([255,255,255])
def z():
    f_x=random.randint(0,3)*block_w+25
    f_y=random.randint(0,3)*block_w+25 
    pygame.draw.circle(screen, [0,255,0], [f_x,f_y], c_r)
def y():
    z()
def x():
    y()
def a():
    x()
def b():
    a()
N=10
block_w=50
c_x=block_w//2
c_y=block_w//2
c_r=(block_w-6)//2

i=0
while i<N:
    j=0
    while j<N:
        pygame.draw.rect(screen,[0,255,0],[i*block_w,j*block_w,block_w,block_w],2)
        j+=1
    i+=1

# 存储一条蛇的坐标,每个元素是(x,y)元组,第0个是头
snake=[]

# color=[255,0,0]
def draw_snake(snake,color=[255,0,0]):
    is_clear=color==[255,255,255]
    direct="right"
    n0=snake[0]
    n1=snake[1]
    if n0[0]==n1[0]:
        if n0[1]>n1[1]:
            direct="down"
        else:
            direct="up"
    elif n0[0]>n1[0]:
        direct="right"
    else:
        direct="left"
    for i,node in enumerate(snake):
        if i==0:
            pygame.draw.circle(screen, color, node, c_r+2)
            if not is_clear:
                r=(c_r+2)//2
                points=[ (node[0],node[1]-r), (node[0],node[1]+r), (node[0]+2*r,node[1]) ]
                if direct=="left":
                    points=[ (node[0],node[1]-r), (node[0],node[1]+r), (node[0]-2*r,node[1]) ]
                elif direct=="up":
                    points=[ (node[0]-r,node[1]), (node[0]+r,node[1]), (node[0],node[1]-2*r) ]
                elif direct=="down":
                    points=[ (node[0]-r,node[1]), (node[0]+r,node[1]), (node[0],node[1]+2*r) ]
                pygame.draw.aalines(screen,[0,0,255],True,points)
        else:
            pygame.draw.circle(screen, color, node, c_r)

# 初始化这条蛇
snake_len=10  #初始长度为6
for i in range(snake_len):
    snake.append((c_x+(snake_len-1-i)*block_w,c_y))

draw_snake(snake)

c_x,c_y=snake[0] # x,y表示蛇头位置

pygame.display.flip()

def is_out_range(c_x,c_y):
    if c_x<=0 or c_x>=block_w*N:
        return True
    if c_y<=0 or c_y>=block_w*N:
        return True
    if is_snake_body(c_x, c_y):
        return True
    return False
def is_snake_body(c_x,c_y):
    shim=block_w//5
    for node in snake:
        if node[0]+shim>=c_x>=node[0]-shim and node[1]+shim>=c_y >= node[1]-shim:
            return True
    return False
f_x=random.randint(0,1)*block_w+25
f_y=random.randint(0,1)*block_w+25
running=True
while running:
    for event in pygame.event.get():
        # print(event)
        if event.type == pygame.QUIT:
            running=False
        elif event.type == pygame.KEYDOWN:
            c_x_old=c_x
            c_y_old=c_y
            # print(event.key)
            pygame.draw.circle(screen, [0,255,0], [f_x,f_y], c_r)#
            if event.key == pygame.K_UP:
                print("向上")
                if not is_out_range(c_x,c_y-1*block_w):
                    c_y-=block_w
            elif event.key == pygame.K_DOWN:
                print("向下")
                if not is_out_range(c_x,c_y+1*block_w):
                    c_y+=1*block_w
            elif event.key == pygame.K_LEFT:
                print("向左")
                if not is_out_range(c_x-1*block_w,c_y):
                    c_x-=1*block_w
            elif event.key == pygame.K_RIGHT:
                print("向右")
                if not is_out_range(c_x+1*block_w,c_y):
                    c_x+=1*block_w

            if c_x != c_x_old or c_y != c_y_old:
                #蛇头位置变动，修改整个蛇的每个节点的坐标
                draw_snake(snake,[255,255,255])
                snake.insert(0, (c_x,c_y))
                del snake[-1]
                draw_snake(snake)
            
                pygame.display.flip()

            snake_len+=1  #初始长度为6
            f=random.randint(0,5)
            if f==3:
                b()
                b()
                b()
                b()
                b()
                b()
                b()
                b()
                b()
                b()
                b()
                b()
                b()
                b()
                b()
                b()
pygame.quit()

import pygame
import time
import random

pygame.init()
pygame.display.set_caption("贪吃蛇 good luck")
screen=pygame.display.set_mode([640,550])
screen.fill([255,255,255])

N=10
block_w=50
c_x=block_w//2
c_y=block_w//2
c_r=(block_w-6)//2

i=0
while i<N:
    j=0
    while j<N:
        pygame.draw.rect(screen,[0,255,0],[i*block_w,j*block_w,block_w,block_w],2)
        j+=1
    i+=1

# 存储一条蛇的坐标,每个元素是(x,y)元组,第0个是头
snake=[]

# color=[255,0,0]
def draw_snake(snake,color=[255,0,0]):
    is_clear=color==[255,255,255]
    direct="right"
    n0=snake[0]
    n1=snake[1]
    if n0[0]==n1[0]:
        if n0[1]>n1[1]:
            direct="down"
        else:
            direct="up"
    elif n0[0]>n1[0]:
        direct="right"
    else:
        direct="left"
    for i,node in enumerate(snake):
        if i==0:
            pygame.draw.circle(screen, color, node, c_r+2)
            if not is_clear:
                r=(c_r+2)//2
                points=[ (node[0],node[1]-r), (node[0],node[1]+r), (node[0]+2*r,node[1]) ]
                if direct=="left":
                    points=[ (node[0],node[1]-r), (node[0],node[1]+r), (node[0]-2*r,node[1]) ]
                elif direct=="up":
                    points=[ (node[0]-r,node[1]), (node[0]+r,node[1]), (node[0],node[1]-2*r) ]
                elif direct=="down":
                    points=[ (node[0]-r,node[1]), (node[0]+r,node[1]), (node[0],node[1]+2*r) ]
                pygame.draw.aalines(screen,[0,0,255],True,points)
        else:
            pygame.draw.circle(screen, color, node, c_r)

# 初始化这条蛇
snake_len=6  #初始长度为6
for i in range(snake_len):
    snake.append((c_x+(snake_len-1-i)*block_w,c_y))

draw_snake(snake)

c_x,c_y=snake[0] # x,y表示蛇头位置

pygame.display.flip()

def is_out_range(c_x,c_y):
    if c_x<=0 or c_x>=block_w*N:
        return True
    if c_y<=0 or c_y>=block_w*N:
        return True
    if is_snake_body(c_x, c_y):
        return True
    return False
def is_snake_body(c_x,c_y):
    shim=block_w//5
    for node in snake:
        if node[0]+shim>=c_x>=node[0]-shim and node[1]+shim>=c_y >= node[1]-shim:
            return True
    return False


running=True
while running:
    for event in pygame.event.get():
        # print(event)
        if event.type == pygame.QUIT:
            running=False
        elif event.type == pygame.KEYDOWN:
            c_x_old=c_x
            c_y_old=c_y
            # print(event.key)
            if event.key == pygame.K_UP:
                print("向上")
                if not is_out_range(c_x,c_y-1*block_w):
                    c_y-=block_w
            elif event.key == pygame.K_DOWN:
                print("向下")
                if not is_out_range(c_x,c_y+1*block_w):
                    c_y+=1*block_w
            elif event.key == pygame.K_LEFT:
                print("向左")
                if not is_out_range(c_x-1*block_w,c_y):
                    c_x-=1*block_w
            elif event.key == pygame.K_RIGHT:
                print("向右")
                if not is_out_range(c_x+1*block_w,c_y):
                    c_x+=1*block_w

            if c_x != c_x_old or c_y != c_y_old:
                #蛇头位置变动，修改整个蛇的每个节点的坐标
                draw_snake(snake,[255,255,255])
                snake.insert(0, (c_x,c_y))
                del snake[-1]
                draw_snake(snake)

                pygame.display.flip()
           
pygame.quit()
"""
import pygame
import random
import time
pygame.init()
screen=pygame.display.set_mode([600,600])
screen.fill([255,255,255])
x=30
y=30
for chang in range(0,10):
    chang = chang*60
    for kuan in range(0,10):
        kuan = kuan*60
        pygame.draw.rect(screen,[0,255,0],[chang,kuan,60,60],1)
        pygame.display.flip()
pygame.draw.circle(screen,[255,0,0],[x,y],25,0)
pygame.display.flip()
def chujie(x,y):
    if x<=0 or x>=630:
        return True
    if y<=0 or y>=630:
        return True
    return False

running=True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running=False
        elif event.type == pygame.KEYDOWN:
            #pygame.draw.circle(screen, [255,255,255], [x,y],25)
            # print(event.key)
            
            if event.key == pygame.K_UP:
                print("向上")
                if not chujie(x,y-60):
                    pygame.draw.circle(screen, [255,255,255], [x,y],25)   
                    pygame.display.flip()                
                    y-=60
            elif event.key == pygame.K_DOWN:
                print("向下")
                if not chujie(x,y+60):
                    pygame.draw.circle(screen, [255,255,255], [x,y],25)
                    pygame.display.flip()
                    y+=60
            elif event.key == pygame.K_LEFT:
                print("向左")
                if not chujie(x-1*60,y):
                    pygame.draw.circle(screen, [255,255,255], [x,y],25)
                    pygame.display.flip()                             
                    x-=1*60
            elif event.key == pygame.K_RIGHT:
                print("向右")
                if not chujie(x+1*60,y):
                    pygame.draw.circle(screen, [255,255,255], [x,y],25)
                    pygame.display.flip()                             
                    x+=1*60
            pygame.draw.circle(screen, [255,0,0], [x,y], 25)
            pygame.display.flip()
pygame.quit
#pygame.draw.circle(screen,[255,0,0],[100,200],50,0)
#pygame.display.flip()      pygame.draw.rect(screen,[0,255,0],[i*block_w,j*block_w,block_w,block_w],2)

import pygame, sys, random
from pygame.locals import *
pygame.init()
mainClock = pygame.time.Clock()
WINDOWWIDTH = 400
WINDOWHEIGHT = 400
rectLength = 18
windowSurface = pygame.display.set_mode((WINDOWWIDTH,WINDOWHEIGHT),0,32)
pygame.display.set_caption('Snake')
BLACK = (0,0,0)
GREEN = (0,255,0)
snakeRect = []
for i in range(7,10):
    snakeRect.append(pygame.Rect(i*(rectLength+2)+1,0+1,rectLength,rectLength))
    food = pygame.Rect(5*(rectLength+2),5*(rectLength+2),rectLength+2,rectLength+2)
moveLeft = True
moveRight = False
moveUp = False
moveDown = False
direction = 1
foodImage = pygame.image.load('cherry.png')
pygame.mixer.music.load('background.mid')
pygame.mixer.music.play(-1,0.0)
pickUpSound = pygame.mixer.Sound('pickup.wav')
while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        if event.type == KEYDOWN:
            if event.key == K_LEFT and moveRight==False:
                moveLeft = True
                moveRight = False
                moveUp = False
                moveDown = False
            if event.key == K_RIGHT and moveLeft==False:
                moveLeft = False
                moveRight = True
                moveUp = False
                moveDown = False
            if event.key == K_UP and moveDown==False:
                moveLeft = False
                moveRight = False
                moveUp = True
                moveDown = False
            if event.key == K_DOWN and moveUp==False:
                moveLeft = False
                moveRight = False
                moveUp = False
                moveDown = True
            head = pygame.Rect(snakeRect[0].left,snakeRect[0].top,snakeRect[0].width,snakeRect[0].height)
            if moveLeft == True:
                head.right = head.left-2
            if moveRight == True:
                head.left = head.right+2
            if moveUp == True:
                head.bottom = head.top-2
            if moveDown == True:
                head.top = head.bottom+2
                snakeRect.insert(0,head)
            if head.right<0 or head.left>WINDOWWIDTH or head.bottom<0 or head.top>WINDOWHEIGHT:
                break
            if food.left == snakeRect[0].left-1 and food.top == snakeRect[0].top-1:
                food.left = random.randint(0,WINDOWWIDTH/20-1)*(rectLength+2)
                food.top = random.randint(0,WINDOWHEIGHT/20-1)*(rectLength+2)
                pickUpSound.play()
            else:   
                snakeRect.pop(len(snakeRect)-1)
                windowSurface.fill(BLACK)
            for i in range(len(snakeRect)):
                pygame.draw.rect(windowSurface,GREEN,snakeRect[i])
                windowSurface.blit(foodImage,food)
            if food.left == 0 and food.right == 0:
                i = 3
                pygame.display.update()
            mainClock.tick(10)"""


# -*- coding: utf-8 -*-
import pygame
import random
import copy

'''
    首先设置蛇的一个运行方向  接下来判断键盘事件在决定蛇的运行方向
    蛇可以运行起来了  那么接下来就是 吃食物增加自己的长度 和 不吃食物在不同的位置显示
'''
# 初始小蛇方向
move_up = False
move_down = False
move_left = False
move_right = True

# 1.1 游戏初始化
pygame.init()
clock = pygame.time.Clock()  # 设置游戏时钟
pygame.display.set_caption("贪吃蛇")  # 初始化标题
screen = pygame.display.set_mode((500, 500))  # 初始化窗口 窗体的大小为 500  500

# 1.2 初始化蛇的位置  蛇的长度  10 10 也就是蛇的 X Y 坐标
snake_list = [[10, 10]]

# 1.3 初始化食物的位置
x = random.randint(10, 490)
y = random.randint(10, 490)
food_point = [x, y]

# 1.4 开启游戏循环
running = True
while running:
    # 1.5 游戏时钟 刷新频率
    clock.tick(10)

    # 1.6 填充背景为白色
    screen.fill([255, 255, 255])

    # 1.9 绘制背景
    for x in range(0, 501, 10):
        pygame.draw.line(screen, (195, 197, 199), (x, 0), (x, 500), 1)
        pygame.draw.line(screen, (195, 197, 199), (0, x), (500, x), 1)

    # 1.7 绘制食物
    # pygame.draw.circle()
    # 用来画圆形，具体包括五个参数：
    # (1)画圆的表面，在本例中用screen创建了一个窗口，所以是画在screen表面上。
    # (2)用什么颜色来画，如用红色[255,0,0]。
    # (3)在什么位置画，[top,left]。
    # (4)直径。
    # (5)线宽，其中0表示完成填充。
    food_rect = pygame.draw.circle(screen, [255, 0, 0], food_point, 25, 0)


    # 1.8 绘制蛇
    snake_rect = []
    for pos in snake_list:
        # 1.8.1 绘制蛇的身子
        snake_rect.append(pygame.draw.circle(screen, [255, 0, 0], pos, 5, 0))

        # 3.1 碰撞检测 如果蛇吃掉食物
        if food_rect.collidepoint(pos):
            # 贪吃蛇吃掉食物
            snake_list.append(food_point)
            # 重置食物位置
            food_point = [random.randint(10, 100), random.randint(1, 499)]
            food_rect = pygame.draw.circle(screen, [255, 0, 0], food_point, 50, 0)
            break

    # # 2.1 移动位置 获取蛇头位置
    # pos = snake_list[0]

    # 2.4 获取蛇的长度，移动蛇的身子
    pos = len(snake_list) - 1
    while pos > 0:
        snake_list[pos] = copy.deepcopy(snake_list[pos - 1])
        pos -= 1

    # 2.2 更改蛇头位置
    if move_up:
        snake_list[pos][1] -= 10
        if snake_list[pos][1] < 0:
            snake_list[pos][1] = 500

    if move_down:
        snake_list[pos][1] += 10
        if snake_list[pos][1] > 500:
            snake_list[pos][1] = 0

    if move_left:
        snake_list[pos][0] -= 10
        if snake_list[pos][0] < 0:
            snake_list[pos][0] = 500

    if move_right:
        snake_list[pos][0] += 10
        if snake_list[pos][0] > 500:
            snake_list[pos][0] = 0
            """
    pygame.draw.circle(screen, [100, 100, 100], [50,50], 10, 0)
    pygame.draw.circle(screen, [100, 100, 100], [450,450], 10, 0)
    if snake_list[pos][1]==50:
        if snake_list[pos][0] == 50:
            snake_list[pos][1] = 450
            snake_list[pos][0] = 450

    if snake_list[pos][1]==450:
        if snake_list[pos][0] == 450:
            snake_list[pos][1] = 50
            snake_list[pos][0] = 50

    pygame.draw.circle(screen, [10, 10, 10], [450,50], 10, 0)
    pygame.draw.circle(screen, [10, 10, 10], [250,250], 10, 0)
    pygame.draw.circle(screen, [10, 10, 10], [50,450], 10, 0)
    if snake_list[pos][1]>440 and snake_list[pos][1]<460:
        if snake_list[pos][0]>40 and snake_list[pos][0]<60:
            snake_list[pos][1] = 250
            snake_list[pos][0] = 250
            
    if snake_list[pos][1]>240 and snake_list[pos][1]<260:
        if snake_list[pos][1]>240 and snake_list[pos][1]<260:
            snake_list[pos][1] = 50
            snake_list[pos][0] = 450
    if snake_list[pos][1]>40 and snake_list[pos][1]<60:
        if snake_list[pos][1]>440 and snake_list[pos][1]<460:
            snake_list[pos][1] = 450
            snake_list[pos][0] = 50 
"""    
    pygame.draw.circle(screen, [10, 10, 10], [60,60], 40, 0)
    if snake_list[pos][1]>=10 and snake_list[pos][1]<=120:
        if snake_list[pos][0]>=10 and snake_list[pos][0]<=120:
            snake_list[pos][1] = food_point[1]
            snake_list[pos][0] = food_point[0]
    # 2.3 键盘控制移动职位
    for event in pygame.event.get():
        # print(event)
        # 判断按下的按键
        if event.type == pygame.KEYDOWN:
            # 上键
            if event.key == pygame.K_UP:
                move_up = True
                move_down = False
                move_left = False
                move_right = False
            # 下键
            if event.key == pygame.K_DOWN:
                move_up = False
                move_down = True
                move_left = False
                move_right = False
            # 左键
            if event.key == pygame.K_LEFT:
                move_up = False
                move_down = False
                move_left = True
                move_right = False
            # 右键
            if event.key == pygame.K_RIGHT:
                move_up = False
                move_down = False
                move_left = False
                move_right = True

    # 3.2 如果蛇吃掉了自己
    head_rect = snake_rect[0]
    count = len(snake_rect)
    while count > 1:
        #if head_rect.colliderect(snake_rect[count - 1]):
         #   running = False
        count -= 10000

    pygame.display.update()
#!/usr/bin/env pyahont3

"""
练习作业：04 
1. 使用pygame 显示窗口 绘制10*10方格，每个方格 50 像素宽
2. 绘制一个圆；可以用方向键控制这个圆在方格内移动
3. 存储圆的位置，在每次重新打开程序时，圆在上次关闭前的方格内
"""
import pygame
import time
import random
fp="python3/study/base.txt"
f=open(fp,"r+")
block_w=60
za=0
c_x=int(f.readline(100))
c_y=int(f.readline(100))
c_x2=random.randint(0,9)*60+30
c_y2=random.randint(0,9)*60+30
while c_x<=0:
    c_x+=30
while c_y<=0:
    c_y+=30

while c_x>=600:
    c_x-=120
while c_y>=600:
    c_y-=120

while (c_x-30)%60!=0:
    c_x+=1
while (c_y-30)%60!=0:
    c_y+=1
# c_y=block_w//2
c_r=(block_w-6)//2


pygame.init()
screen=pygame.display.set_mode([block_w*10,block_w*10])
screen.fill([0,0,0])



def boo(xx,yy):
    f=block_w/2
    pygame.draw.rect(screen,[0,0,0],[xx,yy,f,f],0)
    pygame.draw.rect(screen,[255,0,0],[xx+f,yy,f,f],0)
    pygame.draw.rect(screen,[0,255,0],[xx,yy+f,f,f],0)
    pygame.draw.rect(screen,[0,0,255],[xx+f,yy+f,f,f],0)
N=10
i=0
while i<N:
    j=0
    while j<N:
        pygame.draw.rect(screen,[0,255,0],[i*block_w,j*block_w,block_w,block_w],2)
        #boo(i*block_w,j*block_w)
        j+=1
    i+=1

pygame.draw.circle(screen, [255,0,0], [c_x,c_y], c_r)
pygame.draw.circle(screen, [0,255,0], [c_x2,c_y2], c_r)
pygame.display.flip()
def is_out_range(c_x,c_y):
    if c_x<=0 or c_x>=block_w*10:
        return True
    if c_y<=0 or c_y>=block_w*10:
        return True
    return False
def is_out_ranges(c_x2,c_y2):
    if c_x2<=0 or c_x2>=block_w*10:
        return True
    if c_y2<=0 or c_y2>=block_w*10:
        return True
    return False
running=True
while running:
    for event in pygame.event.get():
        # print(event)
        if event.type == pygame.QUIT:
            running=False
        elif event.type == pygame.KEYDOWN:
            c_x_old=c_x
            c_y_old=c_y
            c_x2_old=c_x2
            c_y2_old=c_y2
            # print(event.key)

            if event.key == pygame.K_UP:
                print("向上")
                if not is_out_range(c_x,c_y-1*block_w):                            
                    c_y-=block_w
            elif event.key == pygame.K_DOWN:
                print("向下")
                if not is_out_range(c_x,c_y+1*block_w):                            
                    c_y+=1*block_w
            elif event.key == pygame.K_LEFT:
                print("向左")
                if not is_out_range(c_x-1*block_w,c_y):                            
                    c_x-=1*block_w
            elif event.key == pygame.K_RIGHT:
                print("向右")
                if not is_out_range(c_x+1*block_w,c_y):                            
                    c_x+=1*block_w
            if c_x==c_x2 and c_y==c_y2:
                za+=1
                print(za)
                c_x2=random.randint(0,9)*60+30
                c_y2=random.randint(0,9)*60+30
                c_x=random.randint(0,9)*60+30
                c_y=random.randint(0,9)*60+30
            zx=0
            c_x3=c_x2-c_x
            c_y3=c_y2-c_y
            while zx==0:
                if c_x>=0:
                    if c_y>=0:
                        x=random.randint(0,6)
                        y=random.randint(1,3)
                    else:
                        x=random.randint(-2,6)
                        y=random.randint(-1,4)
                else:
                    if c_y>0:
                        x=random.randint(0,5)
                        y=random.randint(2,100)
                    else:
                        x=random.randint(-1,3)
                        y=random.randint(-1,3)
                if x<=0 and y<=1 and c_y2-block_w>0:
                    if not is_out_ranges(c_x2,c_y2-1*block_w):                            
                        c_y2-=block_w
                        zx=1
                        continue
                elif x>0 and x<=2 and y==3 and c_x2-block_w>0:
                    if not is_out_ranges(c_x2-1*block_w,c_y2):                            
                        c_x2-=block_w
                        zx=1
                        continue
                elif x>2 and x<=4 and y>=4 and c_y2+block_w<500:
                    if not is_out_ranges(c_x2,c_y2+1*block_w):
                        c_y2+=block_w
                        zx=1
                        continue
                elif x>4 and y>1 and y<=2 and c_x2+block_w<500:
                    if not is_out_ranges(c_x2+1*block_w,c_y2):                            
                        c_x2+=block_w
                        zx=1
                        continue
            pygame.draw.circle(screen, [255,255,255], [c_x2_old,c_y2_old], c_r)
            pygame.draw.circle(screen, [255,255,255], [c_x_old,c_y_old], c_r)
            pygame.draw.circle(screen, [0,255,0], [c_x2,c_y2], c_r)
            #boo(c_x_old-(block_w/2),c_y_old-(block_w/2))
            pygame.draw.circle(screen, [255,0,0], [c_x,c_y], c_r)
            zx=0
            if c_x==c_x2 and c_y==c_y2:
                za+=1
                print(za)
                c_x2=random.randint(0,9)*60+30
                c_y2=random.randint(0,9)*60+30
                c_x=random.randint(0,9)*60+30
                c_y=random.randint(0,9)*60+30
            pygame.display.flip()
    if za>5:
        break


f=open(fp,"w+")
s=str(c_x)
s2=str(c_y)
f.writelines([s+"\n",s2+"\n"])
f.close()
pygame.quit()
#!/usr/bin/env pyahont3

"""
练习作业：01
1. 贪吃蛇游戏
参考游戏：http://www.4399.com/flash/76879_2.htm
"""
#coding=utf-8
# Write By Guobao
# 2017/4//7
#
# 贪吃蛇
# 用#做边界，*做食物，o做身体和头部
# python 3.6.1   
import copy
import random
import os
import msvcrt
# the board class, used to put everything
class board:

    __points =[]

    def __init__(self):
        self.__points.clear()
        for i in range(22):
            line = []
            if i == 0 or i == 21:
                for j in range(22):
                    line.append('#')
            else:
                line.append('#')
                for j in range(20):
                    line.append(' ')
                line.append('#')
            self.__points.append(line)

    def getPoint(self, location):
        return self.__points[location[0]][location[1]]

    def clear(self):
        self.__points.clear()
        for i in range(22):
            line = []
            if i == 0 or i == 21:
                for j in range(22):
                    line.append('#')
            else:
                line.append('#')
                for j in range(20):
                    line.append(' ')#!
                line.append('#')
            self.__points.append(line)

    def put_snake(self, snake_locations):
        # clear the board
        self.clear()

        # put the snake points
        for x in snake_locations:
            self.__points[x[0]][x[1]] = 'o'

        # the head
        x = snake_locations[len(snake_locations) - 1]
        self.__points[x[0]][x[1]] = 'O'

    def put_food(self, food_location):
        self.__points[food_location[0]][food_location[1]] = '*'

    def show(self):
        os.system("cls")
        for i in range(22):
            for j in range(22):
                print(self.__points[i][j], end='')
            print()

# the snake class
class snake:
    __points = []

    def __init__(self):
        for i in range(1, 6):
            self.__points.append([1, i])

    def getPoints(self):
        return self.__points

    # move to the next position
    # give the next head
    def move(self, next_head):
        self.__points.pop(0)
        self.__points.append(next_head)

    # eat the food
    # give the next head
    def eat(self, next_head):
        self.__points.append(next_head)

    # calc the next state
    # and return the direction
    def next_head(self, direction='default'):

        # need to change the value, so copy it
        head = copy.deepcopy(self.__points[len(self.__points) - 1])

        # calc the "default" direction
        if direction == 'default':
            neck = self.__points[len(self.__points) - 2]
            if neck[0] > head[0]:
                direction = 'up'
            elif neck[0] < head[0]:
                direction = 'down'
            elif neck[1] > head[1]:
                direction = 'left'
            elif neck[1] < head[1]:
                direction = 'right'

        if direction == 'up':
            head[0] = head[0] - 1
        elif direction == 'down':
            head[0] = head[0] + 1
        elif direction == 'left':
            head[1] = head[1] - 1
        elif direction == 'right':
            head[1] = head[1] + 1
        return head

# the game
class game:

    board = board()
    snake = snake()
    food = []
    count = 0

    def __init__(self):
        self.new_food()
        self.board.clear()
        self.board.put_snake(self.snake.getPoints())
        self.board.put_food(self.food)

    def new_food(self):
        while 1:
            line=random.randint(2,19)
            column=random.randint(2,19)
            if self.board.getPoint([column, line]) == ' ':
                self.food = [column, line]
                return

    def show(self):
        self.board.clear()
        self.board.put_snake(self.snake.getPoints())
        self.board.put_food(self.food)
        self.board.show()


    def run(self):
        self.board.show()

        # the 'w a s d' are the directions
        operation_dict = {b'w': 'up', b'up': 'up', b's': 'down', b'S': 'down', b'a': 'left', b'A': 'left', b'd': 'right', b'D': 'right'}
        op = msvcrt.getch()

        while op != b'q':
            if op not in operation_dict:
                op = msvcrt.getch()
            else:
                new_head = self.snake.next_head(operation_dict[op])

                # get the food
                if self.board.getPoint(new_head) == '*':
                    self.snake.eat(new_head)
                    self.count = self.count + 1
                    if self.count >= 20:#!
                        self.show()
                        print("Good Job")
                        break
                    else:
                        self.new_food()
                        self.show()

                # 反向一Q日神仙
                elif new_head == self.snake.getPoints()[len(self.snake.getPoints()) - 2]:
                    pass

                # rush the wall
                elif self.board.getPoint(new_head) == '#' or self.board.getPoint(new_head) == 'o':
                    print("GG")
                    break 
                    

                # normal move
                else:
                    self.snake.move(new_head)
                    self.show()
            op = msvcrt.getch()

game().run()
#!/usr/bin/env pyahont3

"""
练习作业：02
2. 俄罗斯方块游戏
"""

'''
公众号：Python代码大全
'''


from __future__ import division
 
import os
import sys
import math
import random
import time
 
from collections import deque
try:
    from pyglet import image  # try import has pip pyglet
    from pyglet.gl import *
    from pyglet.graphics import TextureGroup
    from pyglet.window import key, mouse
except (ImportError,ValueError):
    os.system('pip install pyglet')  # not pip pyglet,try pip it
    from pyglet import image
    from pyglet.gl import *
    from pyglet.graphics import TextureGroup
    from pyglet.window import key, mouse
except (SystemError, ValueError, ImportError):
    image = None  # pip not end
    pyglet.gl = None
    mouse = None
    key = None
 
TICKS_PER_SEC = 60
# Size of sectors used to ease block loading.
SECTOR_SIZE = 16
WALKING_SPEED = 5
FLYING_SPEED = 15
GRAVITY = 20.0
MAX_JUMP_HEIGHT = 1.0 # About the height of a block.
# To derive the formula for calculating jump speed, first solve
#    v_t = v_0 + a * t
# for the time at which you achieve maximum height, where a is the acceleration
# due to gravity and v_t = 0. This gives:
#    t = - v_0 / a
# Use t and the desired MAX_JUMP_HEIGHT to solve for v_0 (jump speed) in
#    s = s_0 + v_0 * t + (a * t^2) / 2
JUMP_SPEED = math.sqrt(2 * GRAVITY * MAX_JUMP_HEIGHT)
TERMINAL_VELOCITY = 50
 
PLAYER_HEIGHT = 2
 
if sys.version_info[0] >= 3:
    xrange = range
 
def cube_vertices(x, y, z, n):
    """ Return the vertices of the cube at position x, y, z with size 2*n.
    """
    return [
        x-n,y+n,z-n, x-n,y+n,z+n, x+n,y+n,z+n, x+n,y+n,z-n,  # top
        x-n,y-n,z-n, x+n,y-n,z-n, x+n,y-n,z+n, x-n,y-n,z+n,  # bottom
        x-n,y-n,z-n, x-n,y-n,z+n, x-n,y+n,z+n, x-n,y+n,z-n,  # left
        x+n,y-n,z+n, x+n,y-n,z-n, x+n,y+n,z-n, x+n,y+n,z+n,  # right
        x-n,y-n,z+n, x+n,y-n,z+n, x+n,y+n,z+n, x-n,y+n,z+n,  # front
        x+n,y-n,z-n, x-n,y-n,z-n, x-n,y+n,z-n, x+n,y+n,z-n,  # back
    ]
 
 
def tex_coord(x, y, n=4):
    """
    Return the bounding vertices of the texture square.
    """
    m = 1.0 / n
    dx = x * m
    dy = y * m
    return dx, dy, dx + m, dy, dx + m, dy + m, dx, dy + m
 
 
def tex_coords(top, bottom, side):
    """
    Return a list of the texture squares for the top, bottom and side.
    """
    top = tex_coord(*top)
    bottom = tex_coord(*bottom)
    side = tex_coord(*side)
    result = []
    result.extend(top)
    result.extend(bottom)
    result.extend(side * 4)
    return result
 
 
TEXTURE_PATH = 'C:\\Users\\wsz\\PycharmProjects\\pycodes\\pycodes\\Minecraft_gamer\\texture_new.png'
 
GRASS = tex_coords((1, 0), (0, 1), (0, 0))
SAND = tex_coords((1, 1), (1, 1), (1, 1))
BRICK = tex_coords((2, 0), (2, 0), (2, 0))
STONE = tex_coords((2, 1), (2, 1), (2, 1))
PARK_STONE = tex_coords((3, 0), (3, 0), (3, 0))
DIRT = tex_coords((0, 1), (0, 1), (0, 1))
TREE_FLOOR = tex_coords((3, 1), (3, 1), (3, 1))
 
FACES = [
    ( 0, 1, 0),
    ( 0,-1, 0),
    (-1, 0, 0),
    ( 1, 0, 0),
    ( 0, 0, 1),
    ( 0, 0,-1),
]
 
 
def normalize(position):
    """ Accepts `position` of arbitrary precision and returns the block
    containing that position.
    Parameters
    ----------
    position : tuple of len 3
    Returns
    -------
    block_position : tuple of ints of len 3
    """
    x, y, z = position
    x, y, z = (int(round(x)), int(round(y)), int(round(z)))
    return (x, y, z)
 
 
def sectorize(position):
    """ Returns a tuple representing the sector for the given `position`.
    Parameters
    ----------
    position : tuple of len 3
    Returns
    -------
    sector : tuple of len 3
    """
    x, y, z = normalize(position)
    x, y, z = x // SECTOR_SIZE, y // SECTOR_SIZE, z // SECTOR_SIZE
    return (x, 0, z)
 
 
class Model(object):
 
    def __init__(self):
 
        # A Batch is a collection of vertex lists for batched rendering.
        self.batch = pyglet.graphics.Batch()
 
        # A TextureGroup manages an OpenGL texture.
        self.group = TextureGroup(image.load(TEXTURE_PATH).get_texture())
 
        # A mapping from position to the texture of the block at that position.
        # This defines all the blocks that are currently in the world.
        self.world = {}
 
        # Same mapping as `world` but only contains blocks that are shown.
        self.shown = {}
 
        # Mapping from position to a pyglet `VertextList` for all shown blocks.
        self._shown = {}
 
        # Mapping from sector to a list of positions inside that sector.
        self.sectors = {}
 
        # Simple function queue implementation. The queue is populated with
        # _show_block() and _hide_block() calls
        self.queue = deque()
 
        self._initialize()
 
    def _initialize(self):
        """ Initialize the world by placing all the blocks.
        """
        n = 80  # 1/2 width and height of world
        s = 1  # step size
        y = 0  # initial y height
        for x in xrange(-n, n + 1, s):
            for z in xrange(-n, n + 1, s):
                # create a layer stone an grass everywhere.
                self.add_block((x, y - 2, z), GRASS, immediate=False)
                self.add_block((x, y - 3, z), STONE, immediate=False)
                if x in (-n, n) or z in (-n, n):
                    # create outer walls.
                    for dy in xrange(-2, 3):
                        self.add_block((x, y + dy, z), STONE, immediate=False)
 
        # generate the hills randomly
        o = n - 10
        for _ in xrange(120):
            a = random.randint(-o, o)  # x position of the hill
            b = random.randint(-o, o)  # z position of the hill
            c = -1  # base of the hill
            h = random.randint(1, 6)  # height of the hill
            s = random.randint(4, 8)  # 2 * s is the side length of the hill
            d = 1  # how quickly to taper off the hills
            t = random.choice([GRASS, SAND, BRICK, PARK_STONE, DIRT, TREE_FLOOR])
            for y in xrange(c, c + h):
                for x in xrange(a - s, a + s + 1):
                    for z in xrange(b - s, b + s + 1):
                        if (x - a) ** 2 + (z - b) ** 2 > (s + 1) ** 2:
                            continue
                        if (x - 0) ** 2 + (z - 0) ** 2 < 5 ** 2:
                            continue
                        self.add_block((x, y, z), t, immediate=False)
                s -= d  # decrement side length so hills taper off
 
    def hit_test(self, position, vector, max_distance=8):
        """ Line of sight search from current position. If a block is
        intersected it is returned, along with the block previously in the line
        of sight. If no block is found, return None, None.
        Parameters
        ----------
        position : tuple of len 3
            The (x, y, z) position to check visibility from.
        vector : tuple of len 3
            The line of sight vector.
        max_distance : int
            How many blocks away to search for a hit.
        """
        m = 8
        x, y, z = position
        dx, dy, dz = vector
        previous = None
        for _ in xrange(max_distance * m):
            key = normalize((x, y, z))
            if key != previous and key in self.world:
                return key, previous
            previous = key
            x, y, z = x + dx / m, y + dy / m, z + dz / m
        return None, None
 
    def exposed(self, position):
        """ Returns False is given `position` is surrounded on all 6 sides by
        blocks, True otherwise.
        """
        x, y, z = position
        for dx, dy, dz in FACES:
            if (x + dx, y + dy, z + dz) not in self.world:
                return True
        return False
 
    def add_block(self, position, texture, immediate=True):
        """ Add a block with the given `texture` and `position` to the world.
        Parameters
        ----------
        position : tuple of len 3
            The (x, y, z) position of the block to add.
        texture : list of len 3
            The coordinates of the texture squares. Use `tex_coords()` to
            generate.
        immediate : bool
            Whether or not to draw the block immediately.
        """
        if position in self.world:
            self.remove_block(position, immediate)
        self.world[position] = texture
        self.sectors.setdefault(sectorize(position), []).append(position)
        if immediate:
            if self.exposed(position):
                self.show_block(position)
            self.check_neighbors(position)
 
    def remove_block(self, position, immediate=True):
        """ Remove the block at the given `position`.
        Parameters
        ----------
        position : tuple of len 3
            The (x, y, z) position of the block to remove.
        immediate : bool
            Whether or not to immediately remove block from canvas.
        """
        del self.world[position]
        self.sectors[sectorize(position)].remove(position)
        if immediate:
            if position in self.shown:
                self.hide_block(position)
            self.check_neighbors(position)
 
    def check_neighbors(self, position):
        """ Check all blocks surrounding `position` and ensure their visual
        state is current. This means hiding blocks that are not exposed and
        ensuring that all exposed blocks are shown. Usually used after a block
        is added or removed.
        """
        x, y, z = position
        for dx, dy, dz in FACES:
            key = (x + dx, y + dy, z + dz)
            if key not in self.world:
                continue
            if self.exposed(key):
                if key not in self.shown:
                    self.show_block(key)
            else:
                if key in self.shown:
                    self.hide_block(key)
 
    def show_block(self, position, immediate=True):
        """ Show the block at the given `position`. This method assumes the
        block has already been added with add_block()
        Parameters
        ----------
        position : tuple of len 3
            The (x, y, z) position of the block to show.
        immediate : bool
            Whether or not to show the block immediately.
        """
        texture = self.world[position]
        self.shown[position] = texture
        if immediate:
            self._show_block(position, texture)
        else:
            self._enqueue(self._show_block, position, texture)
 
    def _show_block(self, position, texture):
        """
        Private implementation of the `show_block()` method.
        Parameters
        ----------
        position : tuple of len 3
        The (x, y, z) position of the block to show.
        texture : list of len 3
        The coordinates of the texture squares. Use `tex_coords()` to
        generate.
        """
        x, y, z = position
        vertex_data = cube_vertices(x, y, z, 0.5)
        texture_data = list(texture)
        # create vertex list
        # FIXME Maybe `add_indexed()` should be used instead
        self._shown[position] = self.batch.add(24, GL_QUADS, self.group,
            ('v3f/static', vertex_data),
            ('t2f/static', texture_data))
 
    def hide_block(self, position, immediate=True):
        """ Hide the block at the given `position`. Hiding does not remove the
        block from the world.
        Parameters
        ----------
        position : tuple of len 3
            The (x, y, z) position of the block to hide.
        immediate : bool
            Whether or not to immediately remove the block from the canvas.
        """
        self.shown.pop(position)
        if immediate:
            self._hide_block(position)
        else:
            self._enqueue(self._hide_block, position)
 
    def _hide_block(self, position):
        """ Private implementation of the 'hide_block()` method.
        """
        self._shown.pop(position).delete()
 
    def show_sector(self, sector):
        """ Ensure all blocks in the given sector that should be shown are
        drawn to the canvas.
        """
        for position in self.sectors.get(sector, []):
            if position not in self.shown and self.exposed(position):
                self.show_block(position, False)
 
    def hide_sector(self, sector):
        """ Ensure all blocks in the given sector that should be hidden are
        removed from the canvas.
        """
        for position in self.sectors.get(sector, []):
            if position in self.shown:
                self.hide_block(position, False)
 
    def change_sectors(self, before, after):
        """ Move from sector `before` to sector `after`. A sector is a
        contiguous x, y sub-region of world. Sectors are used to speed up
        world rendering.
        """
        before_set = set()
        after_set = set()
        pad = 4
        for dx in xrange(-pad, pad + 1):
            for dy in [0]:  # xrange(-pad, pad + 1):
                for dz in xrange(-pad, pad + 1):
                    if dx ** 2 + dy ** 2 + dz ** 2 > (pad + 1) ** 2:
                        continue
                    if before:
                        x, y, z = before
                        before_set.add((x + dx, y + dy, z + dz))
                    if after:
                        x, y, z = after
                        after_set.add((x + dx, y + dy, z + dz))
        show = after_set - before_set
        hide = before_set - after_set
        for sector in show:
            self.show_sector(sector)
        for sector in hide:
            self.hide_sector(sector)
 
    def _enqueue(self, func, *args):
        """ Add `func` to the internal queue.
        """
        self.queue.append((func, args))
 
    def _dequeue(self):
        """ Pop the top function from the internal queue and call it.
        """
        func, args = self.queue.popleft()
        func(*args)
 
    def process_queue(self):
        """ Process the entire queue while taking periodic breaks. This allows
        the game loop to run smoothly. The queue contains calls to
        _show_block() and _hide_block() so this method should be called if
        add_block() or remove_block() was called with immediate=False
        """
        start = time.perf_counter()
        while self.queue and time.perf_counter() - start < 1.0 / TICKS_PER_SEC:
            self._dequeue()
 
    def process_entire_queue(self):
        """
        Process the entire queue with no breaks.
        """
        while self.queue:
            self._dequeue()
 
 
class Window(pyglet.window.Window):
 
    def __init__(self, *args, **kwargs):
        super(Window, self).__init__(*args, **kwargs)
 
        # Whether or not the window exclusively captures the mouse.
        self.exclusive = False
 
        # When flying gravity has no effect and speed is increased.
        self.flying = False
 
        # Strafing is moving lateral to the direction you are facing,
        # e.g. moving to the left or right while continuing to face forward.
        #
        # First element is -1 when moving forward, 1 when moving back, and 0
        # otherwise. The second element is -1 when moving left, 1 when moving
        # right, and 0 otherwise.
        self.strafe = [0, 0]
 
        # Current (x, y, z) position in the world, specified with floats. Note
        # that, perhaps unlike in math class, the y-axis is the vertical axis.
        self.position = (0, 0, 0)
 
        # First element is rotation of the player in the x-z plane (ground
        # plane) measured from the z-axis down. The second is the rotation
        # angle from the ground plane up. Rotation is in degrees.
        #
        # The vertical plane rotation ranges from -90 (looking straight down) to
        # 90 (looking straight up). The horizontal rotation range is unbounded.
        self.rotation = (0, 0)
 
        # Which sector the player is currently in.
        self.sector = None
 
        # The crosshairs at the center of the screen.
        self.reticle = None
 
        # Velocity in the y (upward) direction.
        self.dy = 0
 
        # A list of blocks the player can place. Hit num keys to cycle.
        self.inventory = [BRICK, GRASS, SAND, PARK_STONE, DIRT, TREE_FLOOR]
 
        # The current block the user can place. Hit num keys to cycle.
        self.block = self.inventory[0]
 
        # Convenience list of num keys.
        self.num_keys = [
            key._1, key._2, key._3, key._4, key._5,
            key._6, key._7, key._8, key._9, key._0]
 
        # Instance of the model that handles the world.
        self.model = Model()
 
        # The label that is displayed in the top left of the canvas.
        self.label = pyglet.text.Label('', font_name='Arial', font_size=18,
            x=10, y=self.height - 10, anchor_x='left', anchor_y='top',
            color=(0, 0, 0, 255))
 
        # This call schedules the `update()` method to be called
        # TICKS_PER_SEC. This is the main game event loop.
        pyglet.clock.schedule_interval(self.update, 1.0 / TICKS_PER_SEC)
 
    def set_exclusive_mouse(self, exclusive):
        """ If `exclusive` is True, the game will capture the mouse, if False
        the game will ignore the mouse.
        """
        super(Window, self).set_exclusive_mouse(exclusive)
        self.exclusive = exclusive
 
    def get_sight_vector(self):
        """ Returns the current line of sight vector indicating the direction
        the player is looking.
        """
        x, y = self.rotation
        # y ranges from -90 to 90, or -pi/2 to pi/2, so m ranges from 0 to 1 and
        # is 1 when looking ahead parallel to the ground and 0 when looking
        # straight up or down.
        m = math.cos(math.radians(y))
        # dy ranges from -1 to 1 and is -1 when looking straight down and 1 when
        # looking straight up.
        dy = math.sin(math.radians(y))
        dx = math.cos(math.radians(x - 90)) * m
        dz = math.sin(math.radians(x - 90)) * m
        return (dx, dy, dz)
 
    def get_motion_vector(self):
        """ Returns the current motion vector indicating the velocity of the
        player.
        Returns
        -------
        vector : tuple of len 3
            Tuple containing the velocity in x, y, and z respectively.
        """
        if any(self.strafe):
            x, y = self.rotation
            strafe = math.degrees(math.atan2(*self.strafe))
            y_angle = math.radians(y)
            x_angle = math.radians(x + strafe)
            if self.flying:
                m = math.cos(y_angle)
                dy = math.sin(y_angle)
                if self.strafe[1]:
                    # Moving left or right.
                    dy = 0.0
                    m = 1
                if self.strafe[0] > 0:
                    # Moving backwards.
                    dy *= -1
                # When you are flying up or down, you have less left and right
                # motion.
                dx = math.cos(x_angle) * m
                dz = math.sin(x_angle) * m
            else:
                dy = 0.0
                dx = math.cos(x_angle)
                dz = math.sin(x_angle)
        else:
            dy = 0.0
            dx = 0.0
            dz = 0.0
        return (dx, dy, dz)
 
    def update(self, dt):
        """ This method is scheduled to be called repeatedly by the pyglet
        clock.
        Parameters
        ----------
        dt : float
            The change in time since the last call.
        """
        self.model.process_queue()
        sector = sectorize(self.position)
        if sector != self.sector:
            self.model.change_sectors(self.sector, sector)
            if self.sector is None:
                self.model.process_entire_queue()
            self.sector = sector
        m = 8
        dt = min(dt, 0.2)
        for _ in xrange(m):
            self._update(dt / m)
 
    def _update(self, dt):
        """ Private implementation of the `update()` method. This is where most
        of the motion logic lives, along with gravity and collision detection.
        Parameters
        ----------
        dt : float
            The change in time since the last call.
        """
        # walking
        speed = FLYING_SPEED if self.flying else WALKING_SPEED
        d = dt * speed # distance covered this tick.
        dx, dy, dz = self.get_motion_vector()
        # New position in space, before accounting for gravity.
        dx, dy, dz = dx * d, dy * d, dz * d
        # gravity
        if not self.flying:
            # Update your vertical speed: if you are falling, speed up until you
            # hit terminal velocity; if you are jumping, slow down until you
            # start falling.
            self.dy -= dt * GRAVITY
            self.dy = max(self.dy, -TERMINAL_VELOCITY)
            dy += self.dy * dt
        # collisions
        x, y, z = self.position
        x, y, z = self.collide((x + dx, y + dy, z + dz), PLAYER_HEIGHT)
        self.position = (x, y, z)
 
    def collide(self, position, height):
        """ Checks to see if the player at the given `position` and `height`
        is colliding with any blocks in the world.
        Parameters
        ----------
        position : tuple of len 3
            The (x, y, z) position to check for collisions at.
        height : int or float
            The height of the player.
        Returns
        -------
        position : tuple of len 3
            The new position of the player taking into account collisions.
        """
        # How much overlap with a dimension of a surrounding block you need to
        # have to count as a collision. If 0, touching terrain at all counts as
        # a collision. If .49, you sink into the ground, as if walking through
        # tall grass. If >= .5, you'll fall through the ground.
        pad = 0.25
        p = list(position)
        np = normalize(position)
        for face in FACES:  # check all surrounding blocks
            for i in xrange(3):  # check each dimension independently
                if not face[i]:
                    continue
                # How much overlap you have with this dimension.
                d = (p[i] - np[i]) * face[i]
                if d < pad:
                    continue
                for dy in xrange(height):  # check each height
                    op = list(np)
                    op[1] -= dy
                    op[i] += face[i]
                    if tuple(op) not in self.model.world:
                        continue
                    p[i] -= (d - pad) * face[i]
                    if face == (0, -1, 0) or face == (0, 1, 0):
                        # You are colliding with the ground or ceiling, so stop
                        # falling / rising.
                        self.dy = 0
                    break
        return tuple(p)
 
    def on_mouse_press(self, x, y, button, modifiers):
        """ Called when a mouse button is pressed. See pyglet docs for button
        amd modifier mappings.
        Parameters
        ----------
        x, y : int
            The coordinates of the mouse click. Always center of the screen if
            the mouse is captured.
        button : int
            Number representing mouse button that was clicked. 1 = left button,
            4 = right button.
        modifiers : int
            Number representing any modifying keys that were pressed when the
            mouse button was clicked.
        """
        if self.exclusive:
            vector = self.get_sight_vector()
            block, previous = self.model.hit_test(self.position, vector)
            if (button == mouse.RIGHT) or \
                    ((button == mouse.LEFT) and (modifiers & key.MOD_CTRL)):
                # ON OSX, control + left click = right click.
                if previous:
                    self.model.add_block(previous, self.block)
            elif button == pyglet.window.mouse.LEFT and block:
                texture = self.model.world[block]
                if texture != STONE:
                    self.model.remove_block(block)
        else:
            self.set_exclusive_mouse(True)
 
    def on_mouse_motion(self, x, y, dx, dy):
        """ Called when the player moves the mouse.
        Parameters
        ----------
        x, y : int
            The coordinates of the mouse click. Always center of the screen if
            the mouse is captured.
        dx, dy : float
            The movement of the mouse.
        """
        if self.exclusive:
            m = 0.15
            x, y = self.rotation
            x, y = x + dx * m, y + dy * m
            y = max(-90, min(90, y))
            self.rotation = (x, y)
 
    def on_key_press(self, symbol, modifiers):
        """ Called when the player presses a key. See pyglet docs for key
        mappings.
        Parameters
        ----------
        symbol : int
            Number representing the key that was pressed.
        modifiers : int
            Number representing any modifying keys that were pressed.
        """
        if symbol == key.W:
            self.strafe[0] -= 1
        elif symbol == key.S:
            self.strafe[0] += 1
        elif symbol == key.A:
            self.strafe[1] -= 1
        elif symbol == key.D:
            self.strafe[1] += 1
        elif symbol == key.SPACE:
            if self.dy == 0:
                self.dy = JUMP_SPEED
        elif symbol == key.ESCAPE:
            self.set_exclusive_mouse(False)
        elif symbol == key.TAB:
            self.flying = not self.flying
        elif symbol in self.num_keys:
            index = (symbol - self.num_keys[0]) % len(self.inventory)
            self.block = self.inventory[index]
        elif symbol == key.X:
            self.strafe[0] = 0
            self.strafe[1] = 0
 
    def on_key_release(self, symbol, modifiers):
        """ Called when the player releases a key. See pyglet docs for key
        mappings.
        Parameters
        ----------
        symbol : int
            Number representing the key that was pressed.
        modifiers : int
            Number representing any modifying keys that were pressed.
        """
        if symbol == key.W:
            self.strafe[0] -= 1
        elif symbol == key.S:
            self.strafe[0] += 1
        elif symbol == key.A:
            self.strafe[1] -= 1
        elif symbol == key.D:
            self.strafe[1] += 1
        elif symbol == key.END:
            self.strafe[0] = 0
            self.strafe[1] = 0
 
    def on_resize(self, width, height):
        """ Called when the window is resized to a new `width` and `height`.
        """
        # label
        self.label.y = height - 10
        # reticle
        if self.reticle:
            self.reticle.delete()
        x, y = self.width // 2, self.height // 2
        n = 10
        self.reticle = pyglet.graphics.vertex_list(4,
            ('v2i', (x - n, y, x + n, y, x, y - n, x, y + n))
        )
 
    def set_2d(self):
        """ Configure OpenGL to draw in 2d.
        """
        width, height = self.get_size()
        glDisable(GL_DEPTH_TEST)
        viewport = self.get_viewport_size()
        glViewport(0, 0, max(1, viewport[0]), max(1, viewport[1]))
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        glOrtho(0, max(1, width), 0, max(1, height), -1, 1)
        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()
 
    def set_3d(self):
        """
        Configure OpenGL to draw in 3d.
        """
        width, height = self.get_size()
        glEnable(GL_DEPTH_TEST)
        viewport = self.get_viewport_size()
        glViewport(0, 0, max(1, viewport[0]), max(1, viewport[1]))
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        gluPerspective(65.0, width / float(height), 0.1, 60.0)
        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()
        x, y = self.rotation
        glRotatef(x, 0, 1, 0)
        glRotatef(-y, math.cos(math.radians(x)), 0, math.sin(math.radians(x)))
        x, y, z = self.position
        glTranslatef(-x, -y, -z)
 
    def on_draw(self):
        """
        Called by pyglet to draw the canvas.
        """
        self.clear()
        self.set_3d()
        glColor3d(1, 1, 1)
        self.model.batch.draw()
        self.draw_focused_block()
        self.set_2d()
        self.draw_label()
        self.draw_reticle()
 
    def draw_focused_block(self):
        """
        Draw black edges around the block that is currently under the
        crosshairs.
        """
        vector = self.get_sight_vector()
        block = self.model.hit_test(self.position, vector)[0]
        if block:
            x, y, z = block
            vertex_data = cube_vertices(x, y, z, 0.51)
            glColor3d(0, 0, 0)
            glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)
            pyglet.graphics.draw(24, GL_QUADS, ('v3f/static', vertex_data))
            glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)
 
    def draw_label(self):
        """
        Draw the label in the top left of the screen.
        """
        x, y, z = self.position
        self.label.text = '%02d (%.2f, %.2f, %.2f) %d / %d' % (
            pyglet.clock.get_fps(), x, y, z,
            len(self.model._shown), len(self.model.world))
        self.label.draw()
 
    def draw_reticle(self):
        """
        Draw the crosshairs in the center of the screen.
        """
        glColor3d(0, 0, 0)
        self.reticle.draw(GL_LINES)
 
 
def setup_fog():
    """ Configure the OpenGL fog properties.
    """
    # Enable fog. Fog "blends a fog color with each rasterized pixel fragment's
    # post-texturing color."
    glEnable(GL_FOG)
    # Set the fog color.
    glFogfv(GL_FOG_COLOR, (GLfloat * 4)(0.5, 0.69, 1.0, 1))
    # Say we have no preference between rendering speed and quality.
    glHint(GL_FOG_HINT, GL_DONT_CARE)
    # Specify the equation used to compute the blending factor.
    glFogi(GL_FOG_MODE, GL_LINEAR)
    # How close and far away fog starts and ends. The closer the start and end,
    # the denser the fog in the fog range.
    glFogf(GL_FOG_START, 20.0)
    glFogf(GL_FOG_END, 60.0)
 
 
def setup():
    """ Basic OpenGL configuration.
    """
    # Set the color of "clear", i.e. the sky, in rgba.
    glClearColor(0.5, 0.69, 1.0, 1)
    # Enable culling (not rendering) of back-facing facets -- facets that aren't
    # visible to you.
    glEnable(GL_CULL_FACE)
    # Set the texture minification/magnification function to GL_NEAREST (nearest
    # in Manhattan distance) to the specified texture coordinates. GL_NEAREST
    # "is generally faster than GL_LINEAR, but it can produce textured images
    # with sharper edges because the transition between texture elements is not
    # as smooth."
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
    setup_fog()
 
 
def main():
    window = Window(width=800, height=600, caption='Pyglet', resizable=True)
    # Hide the mouse cursor and prevent the mouse from leaving the window.
    window.set_exclusive_mouse(True)
    setup()
    pyglet.app.run()
 
 
if __name__ == '__main__':
    main()
#!/usr/bin/env pyahont3

"""
练习作业：03
3. 雷电游戏
"""


"""

import pygame.examples.aliens
pygame.examples.aliens.main()
print("1")
pygame.examples.aliens.main()
pygame.examples.aliens.main()
pygame.examples.aliens.main()
pygame.examples.aliens.main()
pygame.examples.aliens.main()
pygame.examples.aliens.main()
pygame.examples.aliens.main()
pygame.examples.aliens.main()
print("2")
pygame.examples.aliens.main()




"""

"""

import random #导入随机模块
num = 1
yin_num = 0
shu_num = 0
while num <= 3:
    if shu_num == 2 or yin_num == 2:
        break
    user = int(input("请出拳 0（石头） 1（剪刀） 2（布）"))
    if user > 2:
        print("不能出大于2的值")
    else:
        data = ["石头", "剪刀", "布"]
        com = random.randint(0, 2)
        print(f"您出的是{(data[user])}，电脑出的是{data[com]}.")
        if user == com:
            print("平局")
            continue
        elif (user == 0 and com == 1) or (user == 1 and com == 2) or (user == 2 and com == 0):
            print("你赢了")
            yin_num += 1
        else:
            print("你输了")
            shu_num += 1
            num += 1
import random#Python数字炸弹小游戏代码：
import time
bomb = random.randint(1, 99)
print(bomb)
start = 0
end = 99
while 1 == 1:
    people = int(input(f"请输入{start}到{end}之间的数:"))#format
    if people > bomb:
        print("大了")
        end = people
    elif people < bomb:
        print("小了")
        start = people
    else:
        print("BOOM!!!")
        break
    print(f"等待电脑了输入{start}到{end}之间的数:")
    time.sleep(1)
    com = random.randint(start + 1, end - 1)
    print("电脑输入：{}".format(com))
    if com > bomb:
        print("大了")
        end = com
    elif com < bomb:
        print("小了")
        start = com
    else:
        print("BOOM!!!")
    break

"""
import random
import time
d=3
z=100
start = 1
end = 100
people,com=0,0
bomb = random.randint(start,end)
A=input("1.打印  2.不打印")
if A=='1':
    print(bomb)
shu=0
yin=0
c=int(input("多少次？"))
cc=0
while cc<c:
    people = int(input(f"请输入{start}到{end}之间的数:"))#format
    if people>end or people<start+1:
        print("不在范围内")
    else:
        time.sleep(0.5)
        if people > bomb:
            print("大了")
            end = people
        elif people < bomb:
            print("小了")
            start = people
        else:
            while d>0:
                print("嘀!")
                print()
                time.sleep(d)
                d=d-0.5
            print("BOOM!!!")
            time.sleep(1)
            print("你输了")
            shu+=1
            cc+=1
            if cc<c:
                d=3
                z=100
                start = 1
                end = 100
                people,com=0,0
                bomb = random.randint(start,end)
                A=input("1.打印  2.不打印")
                if A=='1':
                    print(bomb)
            else:
                break
        time.sleep(0.5)
        print()
        print(f"等待电脑了输入{start}到{end}之间的数:")
        time.sleep(1)
        com = random.randint(start + 1, end - 1)
        print(f"电脑输入：{com}")
        time.sleep(0.5)
        if com > bomb:
            print("大了")
            end = com
        elif com < bomb:
            print("小了")
            start = com
        else:
            while d>0:
                print("嘀!")
                time.sleep(d)
                d=d-1
            print("BOOM!!!")
            time.sleep(1)
            print("你赢了")
            yin+=1
            cc+=1
            if cc<c:
                d=3
                z=100
                start = 1
                end = 100
                people,com=0,0
                bomb = random.randint(start,end)
                A=input("1.打印  2.不打印")
                if A=='1':
                    print(bomb)
            else:
                break
time.sleep(2)
print(yin,shu)
print(f"{(yin/cc)*100}% {(shu/cc)*100}%")

























"""


#!/usr/bin/env python
import pygame,sys,time,random
from pygame.locals import *
# 定义颜色变量
redColour = pygame.Color(255,0,0)
blackColour = pygame.Color(0,0,0)
whiteColour = pygame.Color(255,255,255)
greyColour = pygame.Color(150,150,150)
 
# 定义gameOver函数
def gameOver(playSurface):
    gameOverFont = pygame.font.Font('arial.ttf',72)
    gameOverSurf = gameOverFont.render('Game Over', True, greyColour)
    gameOverRect = gameOverSurf.get_rect()
    gameOverRect.midtop = (320, 10)
    playSurface.blit(gameOverSurf, gameOverRect)
    pygame.display.flip()
    time.sleep(5)
    pygame.quit()
    sys.exit()
 
# 定义main函数
def main():
    # 初始化pygame
    pygame.init()
    fpsClock = pygame.time.Clock()
    # 创建pygame显示层
    playSurface = pygame.display.set_mode((640,480))
    pygame.display.set_caption('Raspberry Snake')
 
 # 初始化变量
snakePosition = [100,100]
snakeSegments = [[100,100],[80,100],[60,100]]
raspberryPosition = [300,300]
raspberrySpawned = 1
direction = 'right'
changeDirection = direction
while True:
    # 检测例如按键等pygame事件
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        if event.type == KEYDOWN:
            # 判断键盘事件
            if event.key == K_RIGHT or event.key == ord('d'):
                changeDirection = 'right'
            if event.key == K_LEFT or event.key == ord('a'):
                changeDirection = 'left'
            if event.key == K_UP or event.key == ord('w'):
                changeDirection = 'up'
            if event.key == K_DOWN or event.key == ord('s'):
                changeDirection = 'down'
            if event.key == K_ESCAPE:
                pygame.event.post(pygame.event.Event(QUIT))
                # 判断是否输入了反方向
    if changeDirection == 'right' and not direction == 'left':
        direction = changeDirection
    if changeDirection == 'left' and not direction == 'right':
        direction = changeDirection
    if changeDirection == 'up' and not direction == 'down':
        direction = changeDirection
    if changeDirection == 'down' and not direction == 'up':
        direction = changeDirection
        # 根据方向移动蛇头的坐标
    if direction == 'right':
        snakePosition[0] += 20
    if direction == 'left':
        snakePosition[0] -= 20
    if direction == 'up':
        snakePosition[1] -= 20
    if direction == 'down':
        snakePosition[1] += 20
        # 增加蛇的长度
    snakeSegments.insert(0,list(snakePosition))
        # 判断是否吃掉了树莓
    if snakePosition[0] == raspberryPosition[0] and snakePosition[1] == raspberryPosition[1]:
        raspberrySpawned = 0
    else:
        snakeSegments.pop()
    # 如果吃掉树莓，则重新生成树莓
    if raspberrySpawned == 0:
        x = random.randrange(1,32)
        y = random.randrange(1,24)
        raspberryPosition = [int(x*20),int(y*20)]
        raspberrySpawned = 1
    # 绘制pygame显示层
    playSurface.fill(blackColour)
    for position in snakeSegments:
        pygame.draw.rect(playSurface,whiteColour,Rect(position[0],position[1],20,20))
        pygame.draw.rect(playSurface,redColour,Rect(raspberryPosition[0], raspberryPosition[1],20,20))
 
    # 刷新pygame显示层
    pygame.display.flip()
    # 判断是否死亡
    if snakePosition[0] > 620 or snakePosition[0] < 0:
        gameOver(playSurface)
    if snakePosition[1] > 460 or snakePosition[1] < 0:
        for snakeBody in snakeSegments[1:]:
            if snakePosition[0] == snakeBody[0] and snakePosition[1] == snakeBody[1]:
                gameOver(playSurface)
    # 控制游戏速度
    fpsClock.tick(5)
 
if __name__ == "__main__":
    main()




"""



"""
import pygame, os
import time
import random
from pygame.sprite import Sprite
from pygame.sprite import Group

def fire_music():
    pass
    # 设置开火音乐
    # effect = pygame.mixer.Sound('sounds/fire.wav')
    # pygame.mixer.Sound.play(effect)

class Boss(Sprite):
    def __init__(self,boss_img_name):
        super().__init__()
        # 加载BOSS图片
        self.image = pygame.image.load('图片/'+boss_img_name+'.png').convert_alpha()
        # 转换BOSS大小
        # self.image = pygame.transform.scale(self.image, (1, 12))
        # 生成BOSS矩形框架
        self.rect = self.image.get_rect()
        self.blood = 1000
        # boss左右移动的速度
        self.speed = 3.5

    def move(self):
        if self.rect.centerx>=512:
            self.speed =-self.speed
        if self.rect.centerx<=0:
            self.speed = -self.speed
        self.rect.centerx +=self.speed



class Enemy(Sprite):
    def __init__(self,screen):
        # 必须设置继承精灵 不然在使用精灵函数时会报错
        super().__init__()
        # 获取屏幕对象
        self.screen = screen
        # 随机 生成5个编号
        alien_num = random.randint(1,5)
        # 随机 加载五个飞机中的某个
        self.image = pygame.image.load('图片/alien_' + str(alien_num) + '.png')
        # picture = pygame.transform.scale(picture, (1280, 720))
        self.image = pygame.transform.scale(self.image,(62,62))
        # 获取飞机的 rect
        self.rect = self.image.get_rect()
        # 击落本机获得的分数
        self.score = 10
        # 加载子弹的图片
        self.bullet_img = pygame.image.load("图片/alien_bullet.png").convert_alpha()
        self.bullet_img = pygame.transform.scale(self.bullet_img, (12, 12))
        # 以下为可以调节子弹尺寸的代码
        # picture = pygame.transform.scale(picture, (1280, 720))
        #飞机的移动速度
        self.speed = random.randint(3,5)

        #生成子弹精灵组合
        self.bullets = Group()
        # 敌机射击频率
        self.shoot_frequency = 0

    # 飞机出现
    def move(self):
        self.rect.top += 5
        #暂时不用射击
        # self.shoot()
        # self.moveBullet()
    # 发射子弹
    def shoot(self):
        if self.shoot_frequency % 200 == 0:
            bullet = Enemy_Bullet(self.bullet_img, self.rect.midbottom)
            self.bullets.add(bullet)
        self.shoot_frequency += 1
        if self.shoot_frequency > 200:
            self.shoot_frequency = 1
    # 删除子弹
    def moveBullet(self):
        for bullet in self.bullets:
            bullet.move()
            if bullet.rect.bottom < 0:
                self.bullets.remove(bullet)
    # 绘制子弹
    def drawBullets(self, scr):
        self.bullets.draw(scr)


class Enemy_Bullet(pygame.sprite.Sprite):
    def __init__(self, init_pos):
        pygame.sprite.Sprite.__init__(self)

        self.image = pygame.image.load("图片/alien_bullet.png").convert_alpha()
        self.image = pygame.transform.scale(self.image, (12, 12))
        self.rect = self.image.get_rect()
        # 敌机子弹初始位置设置
        self.rect.midbottom = init_pos
        self.rect.centery +=36
        self.speed = 8

    def move(self):
        self.rect.top += self.speed
class MyHero(Sprite):
    _rate = 100 # 每帧停留的毫秒数
    def __init__(self,screen,size = 1):
        super().__init__()
        # 获取屏幕对象
        self.screen = screen
        # 获取整张图片
        self.image_big = pygame.image.load('图片/hero.png').convert_alpha()
        # subsurface 形成大图的子表面框架
        # 获取飞机正面图片
        self.image = self.image_big.subsurface(pygame.Rect(120, 0, 318 - 240, 87))
        # 获取飞机正面矩形框架尺寸
        self.rect = self.image.get_rect()
        # 获取屏幕对象矩形
        self.screen_rect = screen.get_rect()
        # 获取屏幕正中x坐标
        self.rect.centerx = self.screen_rect.centerx
        # 获取屏幕底部y坐标
        self.rect.centery = self.screen_rect.bottom - self.rect.height
        # 设置飞机初始位置
        self.centerX = float(self.rect.centerx)
        self.centerY = float(self.rect.centery)
        # 飞机尾焰
        self.air = None
        # 设置飞机尾焰位置
        self.air_rect = pygame.Rect(self.centerX - 20,self.centerY+int((self.rect.height+72)/2)-10-36,40,72)

        #玩家所有发射子弹的集合
        self.bullets = Group()
        self.bullet_image = pygame.image.load('图片/bullet_1.png').convert_alpha()

    # 子弹射击
    def shoot(self):
        # 产生一颗子弹实例
        bullet = Bullet(self.bullet_image,self.rect.midtop)
        # 在group子弹精灵集合中加入子弹
        self.bullets.add(bullet)
    # 子弹删除
    def moveBullet(self):
        # 逐个检查子弹精灵集合 到达屏幕顶端的子弹删除
        for bullet in self.bullets:
            bullet.move()
            if bullet.rect.bottom < 0:
                self.bullets.remove(bullet)
    # 子弹显示
    def drawBullets(self, scr):
        # 将精灵集合中的子弹绘制到屏幕上
        self.bullets.draw(scr)



    # 向上飞时，增加喷射火焰
    def set_air(self, case):
        if case == 'up':
            air = pygame.image.load('图片/air.png').convert_alpha()
            img = air.subsurface(pygame.Rect(80, 0, 50, 87))
            self.air = img
        elif case == 'remove':
            self.air = None

    # 根据移动方向获取飞机移动状态的图片
    def set_image(self, case):
        if case=='left':
            rect = pygame.Rect(195,0,318-248,87)
            image = self.image_big.subsurface(rect)
        elif case =='right':
            rect = pygame.Rect(195,0,318-248,87)
            image = pygame.transform.flip(self.image_big.subsurface(rect), True, False)
        elif case == 'up' or case == 'down':
            rect = pygame.Rect(120, 0, 318 - 240, 87)
            image = self.image_big.subsurface(rect)
        self.image = image

class Bullet(pygame.sprite.Sprite):
    def __init__(self, bullet_img, init_pos):
        pygame.sprite.Sprite.__init__(self)
        self.image = bullet_img
        self.rect = bullet_img.get_rect()
        self.rect.midbottom = init_pos
        self.speed = 25

    def move(self):
        self.rect.top -= self.speed


# 初始化pygame
pygame.init()
# pygame.mixer.init()
# pygame.mixer_music.load('sounds/enviro.mp3') # 加载播放音乐
# pygame.mixer.music.play(-1) #-1 为循环播放
# 设置游戏主题
pygame.display.set_caption('AirCraft')
# 初始化屏幕大小
screen = pygame.display.set_mode((512,768))

# 设置游戏背景图片
# 游戏刚开始时的背景图
bg_img0 = pygame.image.load('图片/start_bg.jpg').convert()
# 加载游戏开始图标
start_img = pygame.image.load('图片/start.png').convert_alpha()
start_rect = start_img.get_rect()
start_rect.centerx = 262
start_rect.centery = 455
#  游戏进行中的背景图
bg_img1 = pygame.image.load('图片/map1.jpg').convert()
bg_img2 = bg_img1.copy()
# 游戏结束时的背景图
bg_img3 = pygame.image.load('图片/map3.jpg').convert()
# 加载游戏结束图标
gameover_img = pygame.image.load('图片/gameover.png').convert_alpha()
# 加载游戏成功图标
gamesuccess = pygame.image.load('图片/success.png').convert_alpha()

# 加载重玩图标
restart_img = pygame.image.load('图片/restart.png').convert_alpha()
restart_rect = restart_img.get_rect()
restart_rect.centerx = 249
restart_rect.centery = 420
# 背景图片初始位置
pos_y1 = -768
pos_y2 = 0

# 实例化BOSS
boss = Boss('boss_1')
bosses = Group()
bosses.add(boss)
# 测试主角图片
# air = pygame.image.load('图片/air.png').convert_alpha()
# img = air.subsurface(pygame.Rect(80, 0, 50, 87))
# image_big = pygame.image.load('图片/hero.png').convert_alpha()
# image = image_big.subsurface(pygame.Rect(195,0,318-248,87))

# 生成我方飞机
student_plane = MyHero(screen)

# 生成敌方飞机
# 生成敌机group
enemies = Group()
# 生成敌机子弹
enemy_bullets = Group()
max_enemies = 9  # 设置敌机数量总数为9
# 敌机随机出现的节奏 下方randint参数 为43,55
ran1,ran2 = 30,40


# 生成计时频率变量
sec = 0
# 生成分数
score = 0
# 设置系统字体
my_font = pygame.font.Font('fonts/msyh.ttf', 18)

# 游戏主循环
# 设置游戏状态  开始 结束
game = 'wait'

while True:
    # 游戏在等待状态
    if game =='wait':
        # 最小游戏框架一个都不能省略
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()

        # 检测鼠标是否按下 重新开始按钮
            if event.type == pygame.MOUSEBUTTONDOWN:
                # 检测鼠标点击位置是否与重启rect重叠
                if start_rect.collidepoint(event.pos):
                    student_plane.__init__(screen)
                    game = 'ing'
        # 游戏结束游戏画面暂停
        screen.blit(bg_img0, (0, 0))
        screen.blit(start_img, start_rect)
        # 测试尾焰位置
        pygame.display.flip()
        time.sleep(0.05)

    # 游戏进行状态
    elif game == 'ing':
        # 设置这3行 监听事件 并且内部设定了延迟防止游戏卡死
        # 屏幕滚动-----------------------------------------------------
        screen.blit(bg_img1, (0, pos_y1))
        screen.blit(bg_img2, (0, pos_y2))
        # 测试尾焰位置
        # screen.blit(img, (100, 100))
        pos_y1 += 1
        pos_y2 += 1
        # 屏幕背景滚动完毕后重置位置
        if pos_y1 >= 0:
            pos_y1 = -768
        if pos_y2 >= 768:
            pos_y2 = 0


        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
            # 监听键盘事件
            # 按键弹起取消飞机向上尾焰 矫正飞机姿势
            if event.type == pygame.KEYUP:
                student_plane.set_image('down')
                student_plane.air = None
            # 发射子弹
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE and len(student_plane.bullets) <6: # 检查子弹集合的数量限制子弹最大数量
                    fire_music()
                    # 产生一颗子弹实例
                    # 在group子弹精灵集合中加入子弹
                    student_plane.shoot()
        # 将精灵集合中的子弹绘制到屏幕上
        student_plane.drawBullets(screen)
        # 逐个检查子弹精灵集合 到达屏幕顶端的子弹删除
        student_plane.moveBullet()

        keys = pygame.key.get_pressed()
        if keys[pygame.K_a]:
            # 设置飞机状态图片
            student_plane.set_image('left')
            if student_plane.rect.centerx>=40:
                student_plane.rect.centerx -=8.5

        elif keys[pygame.K_d]:
            # 设置飞机状态图片
            student_plane.set_image('right')
            if student_plane.rect.centerx <= 478:
                student_plane.rect.centerx +=8.5

        elif keys[pygame.K_w]:
            #设置飞机状态图片
            student_plane.set_image('up')
            student_plane.set_air('up')

            if student_plane.rect.centery >= 45:
                student_plane.rect.centery -=8.5

        elif keys[pygame.K_s]:
            # 设置飞机状态图片
            student_plane.set_image('down')
            if student_plane.rect.centery <= 727:
                student_plane.rect.centery +=8.5

        # 显示飞机
        screen.blit(student_plane.image,student_plane.rect)
        if student_plane.air != None:
            screen.blit(student_plane.air, (student_plane.rect.centerx-30, student_plane.rect.centery+33))

        # 敌机 ---------------------------------------------------------------------------------------

        # 敌机移动
        # 控制时间节奏 sec变量
        sec +=1
        #随机控制生成敌机的节奏
        rhy = random.randint(ran1,ran2)
        # 敌机最多数量

        if sec%rhy ==0 and len(enemies) < max_enemies or sec ==1: # 设置敌机数量总数为9
            # 生成一只敌机
            enemy = Enemy(screen)
            enemy.rect.centerx=random.randint(0,512)
            # 生成上述敌机的子弹
            enemy_bullet = Enemy_Bullet((enemy.rect.centerx,enemy.rect.centery))
            # 敌机group 和 敌机子弹group加载敌机和子弹
            enemies.add(enemy)
            enemy_bullets.add(enemy_bullet)
        # 敌机出现 和 敌机子弹出现
        enemies.draw(screen)
        enemy_bullets.draw(screen)
        # 迭代敌机集合
        for enemy in enemies:
            # 让每个对象移动起来
            enemy.move()
            # 敌机超出屏幕边界后 自动删除敌机
            collision_over1 = pygame.sprite.collide_rect(student_plane, enemy)

            if collision_over1:
                # 为了重启游戏时 防止有旧子弹和飞机存在
                enemies.remove(enemy)
                game = 'over'
            if enemy.rect.bottom >768:
                enemies.remove(enemy)
        for enemy_bullet in enemy_bullets:
            # 让每个对象移动起来
            enemy_bullet.move()

            collision_over2 = pygame.sprite.collide_rect(student_plane, enemy_bullet)
            if collision_over2:
                # 为了重启游戏时 防止有旧子弹和飞机存在
                enemy_bullets.remove(enemy_bullet)
                game = 'over'
            # 敌机子弹超出屏幕边界后 自动删除敌机
            if enemy_bullet.rect.bottom >768:
                enemy_bullets.remove(enemy_bullet)


        #  -----------------------Boss --------------------------
        if score >=140:
            # 小敌机出现的节奏
            ran1,ran2 = 15,25
            max_enemies = 17
            screen.blit(boss.image,boss.rect)
            boss.move()
            for my_bullet in student_plane.bullets:
                hit_boss = pygame.sprite.collide_rect(boss,my_bullet)
                if hit_boss:
                    boss.blood -=1.2
                    score+=1
                if boss.blood <=0:
                    game = 'success'


        # 处理碰撞    ---------------------------碰撞检测--------------------------------------------------
        # 　　参数：
        # 　　group1：精灵组1。
        # 　　group2：精灵组2。
        # 　　dokill1：发生碰撞时，是否销毁精灵组1中的发生碰撞的精灵。
        # 　　dokill2：发生碰撞时，是否销毁精灵组2中的发生碰撞的精灵。
        collisions = pygame.sprite.groupcollide(student_plane.bullets, enemies, True, True)
        if collisions:
            score+=10

        # -----------游戏结束------------

        # 分数和奖励的显示-------------------------------------------------------------------------
        surface1 = my_font.render(u"当前得分：%s"%(score),True,[255,0,0])
        screen.blit(surface1,[20,20])

        # 更新画面
        pygame.display.flip()
        # 设置帧数和延迟
        time.sleep(0.05)

    #游戏结束状态
    elif game == 'over':
        score = 0
        # 最小游戏框架一个都不能省略
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()

        # 检测鼠标是否按下 重新开始按钮
            if event.type == pygame.MOUSEBUTTONDOWN:
                # 检测鼠标点击位置是否与重启rect重叠
                if restart_rect.collidepoint(event.pos):
                    student_plane.__init__(screen)
                    game = 'ing'

        # 游戏结束游戏画面暂停
        screen.blit(bg_img1, (0, pos_y1))
        screen.blit(bg_img2, (0, pos_y2))

        screen.blit(gameover_img, (163, 310))
        screen.blit(restart_img, restart_rect)
        # 测试尾焰位置
        # screen.blit(img, (100, 100))
        pos_y1 += 0
        pos_y2 += 0
        pygame.display.flip()
        time.sleep(0.05)
        # surface2 = my_font.render("Game Over" , True, [255, 0, 0])
        # screen.blit(surface1, [250, 350])
    elif game == 'success':
        score = 0
        boss.blood = 1000
        # 最小游戏框架一个都不能省略
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()

        # 检测鼠标是否按下 重新开始按钮
            if event.type == pygame.MOUSEBUTTONDOWN:
                # 检测鼠标点击位置是否与重启rect重叠
                if restart_rect.collidepoint(event.pos):
                    student_plane.__init__(screen)
                    game = 'ing'

        # 游戏结束游戏画面暂停
        screen.blit(bg_img1, (0, pos_y1))
        screen.blit(bg_img2, (0, pos_y2))

        screen.blit(gamesuccess, (170, 220))
        screen.blit(restart_img, restart_rect)
        # 测试尾焰位置
        # screen.blit(img, (100, 100))
        pos_y1 += 0
        pos_y2 += 0
        pygame.display.flip()
        time.sleep(0.05)



"""



"""

#Lucifer的雷电
import pygame, os
import time
import random
from pygame.sprite import Sprite
from pygame.sprite import Group
 
 
def fire_music():
 
    # 设置开火音乐
    effect = pygame.mixer.Sound('sounds/fire.wav')
    pygame.mixer.Sound.play(effect)
 
class Boss(Sprite):
    def __init__(self,boss_img_name):
        super().__init__()
        # 加载BOSS图片
        self.image = pygame.image.load('图片/boss_1.png').convert_alpha()
        # 转换BOSS大小
        # self.image = pygame.transform.scale(self.image, (1, 12))
        # 生成BOSS矩形框架
        self.rect = self.image.get_rect()
        self.blood = 1000
        # boss左右移动的速度
        self.speed = 3.5
 
    def move(self):
        if self.rect.centerx>=512:
            self.speed =-self.speed
        if self.rect.centerx<=0:
            self.speed = -self.speed
        self.rect.centerx +=self.speed
 
 
 
class Enemy(Sprite):
    def __init__(self,screen):
        # 必须设置继承精灵 不然在使用精灵函数时会报错
        super().__init__()
        # 获取屏幕对象
        self.screen = screen
        # 随机 生成5个编号
        alien_num = random.randint(1,5)
        # 随机 加载五个飞机中的某个
        self.image = pygame.image.load('图片/alien_' + str(alien_num) + '.png')
        # picture = pygame.transform.scale(picture, (1280, 720))
        self.image = pygame.transform.scale(self.image,(62,62))
        # 获取飞机的 rect
        self.rect = self.image.get_rect()
        # 击落本机获得的分数
        self.score = 10
        # 加载子弹的图片
        self.bullet_img = pygame.image.load("图片/alien_bullet.png").convert_alpha()
        self.bullet_img = pygame.transform.scale(self.bullet_img, (12, 12))
        # 以下为可以调节子弹尺寸的代码
        # picture = pygame.transform.scale(picture, (1280, 720))
        #飞机的移动速度
        self.speed = random.randint(3,5)
 
        #生成子弹精灵组合
        self.bullets = Group()
        # 敌机射击频率
        self.shoot_frequency = 0
 
    # 飞机出现
    def move(self):
        self.rect.top += 5
        #暂时不用射击
        # self.shoot()
        # self.moveBullet()
    # 发射子弹
    def shoot(self):
        if self.shoot_frequency % 200 == 0:
            bullet = Enemy_Bullet(self.bullet_img, self.rect.midbottom)
            self.bullets.add(bullet)
        self.shoot_frequency += 1
        if self.shoot_frequency > 200:
            self.shoot_frequency = 1
    # 删除子弹
    def moveBullet(self):
        for bullet in self.bullets:
            bullet.move()
            if bullet.rect.bottom < 0:
                self.bullets.remove(bullet)
    # 绘制子弹
    def drawBullets(self, scr):
        self.bullets.draw(scr)
 
 
class Enemy_Bullet(pygame.sprite.Sprite):
    def __init__(self, init_pos):
        pygame.sprite.Sprite.__init__(self)
 
        self.image = pygame.image.load("图片/alien_bullet.png").convert_alpha()
        self.image = pygame.transform.scale(self.image, (12, 12))
        self.rect = self.image.get_rect()
        # 敌机子弹初始位置设置
        self.rect.midbottom = init_pos
        self.rect.centery +=36
        self.speed = 8
 
    def move(self):
        self.rect.top += self.speed
class MyHero(Sprite):
    _rate = 100 # 每帧停留的毫秒数
    def __init__(self,screen,size = 1):
        super().__init__()
        # 获取屏幕对象
        self.screen = screen
        # 获取整张图片
        self.image_big = pygame.image.load('图片/hero.png').convert_alpha()
        # subsurface 形成大图的子表面框架
        # 获取飞机正面图片
        self.image = self.image_big.subsurface(pygame.Rect(120, 0, 318 - 240, 87))
        # 获取飞机正面矩形框架尺寸
        self.rect = self.image.get_rect()
        # 获取屏幕对象矩形
        self.screen_rect = screen.get_rect()
        # 获取屏幕正中x坐标
        self.rect.centerx = self.screen_rect.centerx
        # 获取屏幕底部y坐标
        self.rect.centery = self.screen_rect.bottom - self.rect.height
        # 设置飞机初始位置
        self.centerX = float(self.rect.centerx)
        self.centerY = float(self.rect.centery)
        # 飞机尾焰
        self.air = None
        # 设置飞机尾焰位置
        self.air_rect = pygame.Rect(self.centerX - 20,self.centerY+int((self.rect.height+72)/2)-10-36,40,72)
 
        #玩家所有发射子弹的集合
        self.bullets = Group()
        self.bullet_image = pygame.image.load('图片/bullet_1.png').convert_alpha()
 
    # 子弹射击
    def shoot(self):
        # 产生一颗子弹实例
        bullet = Bullet(self.bullet_image,self.rect.midtop)
        # 在group子弹精灵集合中加入子弹
        self.bullets.add(bullet)
    # 子弹删除
    def moveBullet(self):
        # 逐个检查子弹精灵集合 到达屏幕顶端的子弹删除
        for bullet in self.bullets:
            bullet.move()
            if bullet.rect.bottom < 0:
                self.bullets.remove(bullet)
    # 子弹显示
    def drawBullets(self, scr):
        # 将精灵集合中的子弹绘制到屏幕上
        self.bullets.draw(scr)
 
 
 
    # 向上飞时，增加喷射火焰
    def set_air(self, case):
        if case == 'up':
            air = pygame.image.load('图片/air.png').convert_alpha()
            img = air.subsurface(pygame.Rect(80, 0, 50, 87))
            self.air = img
        elif case == 'remove':
            self.air = None
 
    # 根据移动方向获取飞机移动状态的图片
    def set_image(self, case):
        if case=='left':
            rect = pygame.Rect(195,0,318-248,87)
            image = self.image_big.subsurface(rect)
        elif case =='right':
            rect = pygame.Rect(195,0,318-248,87)
            image = pygame.transform.flip(self.image_big.subsurface(rect), True, False)
        elif case == 'up' or case == 'down':
            rect = pygame.Rect(120, 0, 318 - 240, 87)
            image = self.image_big.subsurface(rect)
        self.image = image
 
class Bullet(pygame.sprite.Sprite):
    def __init__(self, bullet_img, init_pos):
        pygame.sprite.Sprite.__init__(self)
        self.image = bullet_img
        self.rect = bullet_img.get_rect()
        self.rect.midbottom = init_pos
        self.speed = 25
 
    def move(self):
        self.rect.top -= self.speed
 
 
# 初始化pygame
pygame.init()
pygame.mixer.init() # 加载播放音乐#-1 为循环播放
# 设置游戏主题
pygame.display.set_caption('Lucifer的雷电')
# 初始化屏幕大小
screen = pygame.display.set_mode((512,768))
 
# 设置游戏背景图片bg_img0 = pygame.image.load('图片/start_bg.jpg').convert()
# 游戏刚开始时的背景图
bg_img0 = pygame.image.load('图片/start_bg.jpg').convert()
# 加载游戏开始图标
start_img = pygame.image.load('图片/start.png').convert_alpha()
start_rect = start_img.get_rect()
start_rect.centerx = 262
start_rect.centery = 455
#  游戏进行中的背景图
bg_img1 = pygame.image.load('图片/map1.jpg').convert()
bg_img2 = bg_img1.copy()
# 游戏结束时的背景图
bg_img3 = pygame.image.load('图片/map3.jpg').convert()
# 加载游戏结束图标
gameover_img = pygame.image.load('图片/gameover.png').convert_alpha()
# 加载游戏成功图标
gamesuccess = pygame.image.load('图片/success.png').convert_alpha()
 
# 加载重玩图标
restart_img = pygame.image.load('图片/restart.png').convert_alpha()
restart_rect = restart_img.get_rect()
restart_rect.centerx = 249
restart_rect.centery = 420
# 背景图片初始位置
pos_y1 = -768
pos_y2 = 0
 
# 实例化BOSS
boss = Boss('boss_1')
bosses = Group()
bosses.add(boss)
# 测试主角图片
# air = pygame.image.load('图片/air.png').convert_alpha()
# img = air.subsurface(pygame.Rect(80, 0, 50, 87))
# image_big = pygame.image.load('图片/hero.png').convert_alpha()
# image = image_big.subsurface(pygame.Rect(195,0,318-248,87))
 
# 生成我方飞机
student_plane = MyHero(screen)
 
# 生成敌方飞机
# 生成敌机group
enemies = Group()
# 生成敌机子弹
enemy_bullets = Group()
max_enemies = 9  # 设置敌机数量总数为9
# 敌机随机出现的节奏 下方randint参数 为43,55
ran1,ran2 = 30,40
 
#己方生命值
life = 3
# 生成计时频率变量
sec = 0
# 生成分数
score = 0
# 设置系统字体
my_font = pygame.font.Font('fonts/msyh.ttf', 18)
 
# 游戏主循环
# 设置游戏状态  开始 结束
game = 'wait'
 
while True:
    # 游戏在等待状态
    if game =='wait':
        # 最小游戏框架一个都不能省略
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
 
        # 检测鼠标是否按下 重新开始按钮
            if event.type == pygame.MOUSEBUTTONDOWN:
                # 检测鼠标点击位置是否与重启rect重叠
                if start_rect.collidepoint(event.pos):
                    student_plane.__init__(screen)
                    game = 'ing'
        # 游戏结束游戏画面暂停
        screen.blit(bg_img0, (0, 0))
        screen.blit(start_img, start_rect)
        # 测试尾焰位置
        pygame.display.flip()
        time.sleep(0.05)
 
    # 游戏进行状态
    elif game == 'ing':
        # 设置这3行 监听事件 并且内部设定了延迟防止游戏卡死
        # 屏幕滚动-----------------------------------------------------
        screen.blit(bg_img1, (0, pos_y1))
        screen.blit(bg_img2, (0, pos_y2))
        # 测试尾焰位置
        # screen.blit(img, (100, 100))
        pos_y1 += 1
        pos_y2 += 1
        # 屏幕背景滚动完毕后重置位置
        if pos_y1 >= 0:
            pos_y1 = -768
        if pos_y2 >= 768:
            pos_y2 = 0
 
 
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
            # 监听键盘事件
            # 按键弹起取消飞机向上尾焰 矫正飞机姿势
            if event.type == pygame.KEYUP:
                student_plane.set_image('down')
                student_plane.air = None
            # 发射子弹
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE and len(student_plane.bullets) <6: # 检查子弹集合的数量限制子弹最大数量
                    fire_music()
                    # 产生一颗子弹实例
                    # 在group子弹精灵集合中加入子弹
                    student_plane.shoot()
        # 将精灵集合中的子弹绘制到屏幕上
        student_plane.drawBullets(screen)
        # 逐个检查子弹精灵集合 到达屏幕顶端的子弹删除
        student_plane.moveBullet()
 
        keys = pygame.key.get_pressed()
        if keys[pygame.K_a]:
            # 设置飞机状态图片
            student_plane.set_image('left')
            if student_plane.rect.centerx>=40:
                student_plane.rect.centerx -=8.5
 
        elif keys[pygame.K_d]:
            # 设置飞机状态图片
            student_plane.set_image('right')
            if student_plane.rect.centerx <= 478:
                student_plane.rect.centerx +=8.5
 
        elif keys[pygame.K_w]:
            #设置飞机状态图片
            student_plane.set_image('up')
            student_plane.set_air('up')
 
            if student_plane.rect.centery >= 45:
                student_plane.rect.centery -=8.5
 
        elif keys[pygame.K_s]:
            # 设置飞机状态图片
            student_plane.set_image('down')
            if student_plane.rect.centery <= 727:
                student_plane.rect.centery +=8.5
 
        # 显示飞机
        screen.blit(student_plane.image,student_plane.rect)
        if student_plane.air != None:
            screen.blit(student_plane.air, (student_plane.rect.centerx-30, student_plane.rect.centery+33))
 
        # 敌机 ---------------------------------------------------------------------------------------
 
        # 敌机移动
        # 控制时间节奏 sec变量
        sec +=1
        #随机控制生成敌机的节奏
        rhy = random.randint(ran1,ran2)
        # 敌机最多数量
 
        if sec%rhy ==0 and len(enemies) < max_enemies or sec ==1: # 设置敌机数量总数为9
            # 生成一只敌机
            enemy = Enemy(screen)
            enemy.rect.centerx=random.randint(0,512)
            # 生成上述敌机的子弹
            enemy_bullet = Enemy_Bullet((enemy.rect.centerx,enemy.rect.centery))
            # 敌机group 和 敌机子弹group加载敌机和子弹
            enemies.add(enemy)
            enemy_bullets.add(enemy_bullet)
        # 敌机出现 和 敌机子弹出现
        enemies.draw(screen)
        enemy_bullets.draw(screen)
        # 迭代敌机集合
        for enemy in enemies:
            # 让每个对象移动起来
            enemy.move()
            # 敌机超出屏幕边界后 自动删除敌机
            collision_over1 = pygame.sprite.collide_rect(student_plane, enemy)
 
            if collision_over1:
                # 为了重启游戏时 防止有旧子弹和飞机存在
                enemies.remove(enemy)
                life -= 1
 
            if enemy.rect.bottom >768:
                enemies.remove(enemy)
        for enemy_bullet in enemy_bullets:
            # 让每个对象移动起来
            enemy_bullet.move()
 
            collision_over2 = pygame.sprite.collide_rect(student_plane, enemy_bullet)
            if collision_over2:
                # 为了重启游戏时 防止有旧子弹和飞机存在
                enemy_bullets.remove(enemy_bullet)
                life -= 1
 
            # 敌机子弹超出屏幕边界后 自动删除敌机
            if enemy_bullet.rect.bottom >768:
                enemy_bullets.remove(enemy_bullet)
 
 
        if life <=0:
            game = "over"
            enemy_bullets.remove(enemy_bullet)
 
        #  -----------------------Boss --------------------------
        if score >=140:
            # 小敌机出现的节奏
            ran1,ran2 = 15,25
            max_enemies = 17
            screen.blit(boss.image,boss.rect)
            boss.move()
            for my_bullet in student_plane.bullets:
                hit_boss = pygame.sprite.collide_rect(boss,my_bullet)
                if hit_boss:
                    boss.blood -=1.2
                    score+=1
                if boss.blood <=0:
                    game = 'success'
 
 
        # 处理碰撞    ---------------------------碰撞检测--------------------------------------------------
        # 　　参数：
        # 　　group1：精灵组1。
        # 　　group2：精灵组2。
        # 　　dokill1：发生碰撞时，是否销毁精灵组1中的发生碰撞的精灵。
        # 　　dokill2：发生碰撞时，是否销毁精灵组2中的发生碰撞的精灵。
        collisions = pygame.sprite.groupcollide(student_plane.bullets, enemies, True, True)
        if collisions:
            score+=10
 
        # -----------游戏结束------------
 
        # 分数和奖励的显示-------------------------------------------------------------------------
        surface1 = my_font.render(u"当前得分：%s"%(score),True,[0,255,0])
        screen.blit(surface1,[20,20])
        surface2 = my_font.render(u"当前生命数：%s" % (life), True, [255, 0, 0])
        screen.blit(surface2, [200, 20])
 
 
        # 更新画面
        pygame.display.flip()
        # 设置帧数和延迟
        time.sleep(0.05)
 
    #游戏结束状态
    elif game == 'over':
        score = 0
        life = 3
        # 最小游戏框架一个都不能省略
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
 
        # 检测鼠标是否按下 重新开始按钮
            if event.type == pygame.MOUSEBUTTONDOWN:
                # 检测鼠标点击位置是否与重启rect重叠
                if restart_rect.collidepoint(event.pos):
                    student_plane.__init__(screen)
                    game = 'ing'
 
        # 游戏结束游戏画面暂停
        screen.blit(bg_img1, (0, pos_y1))
        screen.blit(bg_img2, (0, pos_y2))
 
        screen.blit(gameover_img, (163, 310))
        screen.blit(restart_img, restart_rect)
        # 测试尾焰位置
        # screen.blit(img, (100, 100))
        pos_y1 += 0
        pos_y2 += 0
        pygame.display.flip()
        time.sleep(0.05)
        # surface2 = my_font.render("Game Over" , True, [255, 0, 0])
        # screen.blit(surface1, [250, 350])
    elif game == 'success':
        score = 0
        life = 3
        boss.blood = 1000
        # 最小游戏框架一个都不能省略
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
 
        # 检测鼠标是否按下 重新开始按钮
            if event.type == pygame.MOUSEBUTTONDOWN:
                # 检测鼠标点击位置是否与重启rect重叠
                if restart_rect.collidepoint(event.pos):
                    student_plane.__init__(screen)
                    game = 'ing'
 
        # 游戏结束游戏画面暂停
        screen.blit(bg_img1, (0, pos_y1))
        screen.blit(bg_img2, (0, pos_y2))
 
        screen.blit(gamesuccess, (170, 220))
        screen.blit(restart_img, restart_rect)
        # 测试尾焰位置
        # screen.blit(img, (100, 100))
        pos_y1 += 0
        pos_y2 += 0
        pygame.display.flip()
        time.sleep(0.05)
"""